Recommended preparation: set up a Django project and read the Django tutorial overview before trying the code.
Use bulk_create() to insert many Django model instances efficiently. The example imports a list of student tuples and validates each row before calling the database. It does not delete existing student data.
Django shell — add three new students in one batch
from students.models import Student
rows = [
("John Deo", "Four", 75, "female"),
("Max Ruin", "Three", 85, "male"),
("Arnold", "Three", 55, "male"),
]
items = [Student(name=n, cl=c, mark=m, gender=g) for n, c, m, g in rows]
Student.objects.bulk_create(items)
The provided sample dataset stores each row as an ID, name, class, mark and gender. For new inserts, omit the ID and let Django assign a primary key. The companion text file contains 35 sample rows.
students/models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
cl = models.CharField(max_length=20, db_column="class")
mark = models.PositiveSmallIntegerField()
gender = models.CharField(max_length=20)
def __str__(self):
return self.name
Run the migrations explained in Django MySQL before inserting any rows. MySQL and SQLite both support the Django ORM’s bulk_create().
The accompanying sample student list contains tuples in the order (id, name, class, mark, gender). For brand-new rows, you can ignore the source ID and use automatically generated IDs. If an ID is deliberately preserved, you must handle duplicates and conflicts explicitly.
Map original five-item rows to model instances
# In python manage.py shell, after defining l1 as the tuples in the sample file:
from students.models import Student
items = [
Student(name=name, cl=cl, mark=mark, gender=gender)
for _id, name, cl, mark, gender in l1
]
created = Student.objects.bulk_create(items, batch_size=500)
print("Inserted:", len(created))
Batch imports change database data. Do not expose an unauthenticated view that inserts rows whenever somebody loads a page. Prefer a Django management command, controlled admin action or an authenticated POST endpoint with permission checks.
Safe pattern: explicit management command
# students/management/commands/import_demo.py
from django.core.management.base import BaseCommand
from students.models import Student
class Command(BaseCommand):
help = "Add three demonstration student rows"
def handle(self, *args, **options):
rows = [("John Deo", "Four", 75, "female"),
("Max Ruin", "Three", 85, "male"),
("Arnold", "Three", 55, "male")]
created = Student.objects.bulk_create(
[Student(name=n, cl=c, mark=m, gender=g) for n, c, m, g in rows],
batch_size=500,
)
self.stdout.write(self.style.SUCCESS(f"Inserted {len(created)} rows"))
Run the import only when you intentionally want additional demonstration rows
python manage.py import_demo
bulk_create() does not de-duplicate input automatically. For repeatable imports, choose a real unique business key or an external import identifier, add a database constraint, and use a matching strategy. Display names are not a safe unique key for students.
Illustrative get_or_create (not a substitute for a database unique constraint)
from django.db import transaction
from students.models import Student
with transaction.atomic():
Student.objects.get_or_create(
name="Alex John",
cl="Four",
defaults={"mark": 55, "gender": "male"},
)
Student.objects.all().delete() in a routine that merely imports examples. That deletes every row. Only perform bulk deletion when explicitly intended, authorized, and backed up.Use an atomic transaction for related changes
from django.db import transaction
from students.models import Student
rows = [("Test A", "Five", 70, "male"), ("Test B", "Six", 88, "female")]
with transaction.atomic():
objects = [Student(name=n, cl=c, mark=m, gender=g) for n, c, m, g in rows]
Student.objects.bulk_create(objects, batch_size=500)
A transaction helps group related database writes. bulk_create() does not call each model’s overridden save() method or send the usual per-object save signals. If you rely on custom save logic, check the method’s documented limitations before switching from a loop of save() calls.
Simple validation before a batch insert
def validate_rows(rows):
for name, cl, mark, gender in rows:
if not name or len(name) > 100:
raise ValueError("Invalid student name")
if not isinstance(mark, int) or not 0 <= mark <= 100:
raise ValueError("Mark must be an integer from 0 to 100")
return rows
Check row count and recent records
from students.models import Student
print("Rows in table:", Student.objects.count())
for student in Student.objects.order_by("-id")[:5]:
print(student.pk, student.name, student.mark)
The sample data also links to the SQL student data example. For reading inserted records on a web page, continue to Django MySQL display.
bulk_create() does not call full_clean() for each model; validate first.Validate the five-column sample tuples
sample = [(1, "John Deo", "Four", 75, "female"),
(2, "Max Ruin", "Three", 85, "male")]
assert all(len(row) == 5 for row in sample)
Divide a large iterable into bounded chunks
from itertools import islice
def batches(iterable, size):
it = iter(iterable)
while chunk := list(islice(it, size)):
yield chunk
Call bulk_create for each import batch
rows = [("Student 1", "Four", 70, "male"),
("Student 2", "Five", 72, "female")]
for batch in batches(rows, 500):
Student.objects.bulk_create(
[Student(name=n, cl=c, mark=m, gender=g) for n, c, m, g in batch]
)
Summarize the imported rows by class
from django.db.models import Count
print(Student.objects.values("cl").annotate(total=Count("id")))
No. It performs bulk operations and bypasses each object’s save() method and per-object save signals.
Yes if they are valid and unique in the target table, but this may conflict with existing rows. Auto-assigned IDs are safer for a beginner example.
GET should not trigger a destructive or state-changing operation. Use an explicit management command or a protected POST action.
Previous: Insert form data
Next: Display and filter MySQL rows
Browse the complete Django tutorial series.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.