Insert Multiple Rows with Django bulk_create()

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.

On this page — Show page sectionsHide page sections

Prepare the Student model

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().

Import records from the supplied sample data

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))

Use a management command instead of a public GET URL

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

Prevent duplicate imports

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"},
    )
Avoid calling 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.

Batch size, transactions and error handling

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.

Validate imported rows

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

Verify inserted records

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.

Common bulk-insert problems

  • IntegrityError on duplicate primary keys: do not supply IDs for new rows unless necessary.
  • Silent validation gaps: bulk_create() does not call full_clean() for each model; validate first.
  • Unexpected duplicates: use an appropriate unique constraint and idempotent import design.
  • Memory usage: process large inputs in batches instead of materializing an enormous list.
  • Signals not firing: review the bulk_create behavior and use per-object saving when those hooks are required.

Additional import patterns

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")))
The sample data file is available for the import exercises. The demonstrated imports omit source IDs, so they do not attempt to overwrite existing primary keys.

Frequently asked questions

Does bulk_create() call save() for every record?

No. It performs bulk operations and bypasses each object’s save() method and per-object save signals.

Can I keep the IDs from the original 35-row list?

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.

Why should a batch insert not run from a GET request?

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.

Additional references

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer