Full answer
Importing 50,000 exam results with save() in a loop sends 50,000 INSERT statements. The bulk methods batch them.
bulk_create(objs, batch_size=1000)
- Inserts in batches. On PostgreSQL, SQLite 3.35+ and MariaDB 10.5+, primary keys are set on the objects afterwards.
ignore_conflicts=Trueskips rows that violate a unique constraint (primary keys are not set then).update_conflicts=True, unique_fields=[...], update_fields=[...](Django 4.1+) turns it into an upsert: insert new rows, update existing ones. Great for nightly syncs from another system.
bulk_update(objs, ["score"], batch_size=500)
- Builds
UPDATE ... SET score = CASE id WHEN 1 THEN ... ENDper batch. Large batches create very long SQL, so setbatch_size. - Returns the number of rows matched (Django 4.0+).
QuerySet.update(...) is the fastest when all rows get the same change or an F() expression.
What bulk methods skip:
Model.save()overrides (so custom logic in save does not run).pre_save/post_savesignals.full_clean()validation. Database constraints still apply.auto_nowfields are set bybulk_createbutbulk_updateonly updates fields you list, so includeupdated_atexplicitly and set it yourself.
Good import pattern:
- Read and validate input in Python (a form or serializer per row, or a vectorised check).
- Upsert in batches inside
transaction.atomic()per batch. - Report rows inserted, updated and rejected.
- Trigger side effects (cache clear, notifications) once after the batch, not per row.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import connection, models
from django.test.utils import CaptureQueriesContext
class Result(models.Model):
roll_no = models.CharField(max_length=10)
subject = models.CharField(max_length=20)
score = models.IntegerField()
class Meta:
app_label = "school"
constraints = [models.UniqueConstraint(fields=["roll_no", "subject"], name="one_result")]
with connection.schema_editor() as editor:
editor.create_model(Result)
rows = [Result(roll_no=f"R{i:03d}", subject="Maths", score=50 + i % 50) for i in range(1000)]
with CaptureQueriesContext(connection) as ctx:
Result.objects.bulk_create(rows, batch_size=250)
print("inserted:", Result.objects.count(), "queries:", len(ctx.captured_queries))
objs = list(Result.objects.filter(roll_no__in=["R001", "R002"]).order_by("roll_no"))
for o in objs:
o.score += 5
print("bulk_update rows:", Result.objects.bulk_update(objs, ["score"]))
nightly_feed = [
Result(roll_no="R001", subject="Maths", score=99), # exists -> update
Result(roll_no="R1000", subject="Maths", score=77), # new -> insert
]
Result.objects.bulk_create(nightly_feed, update_conflicts=True,
unique_fields=["roll_no", "subject"], update_fields=["score"])
print(list(Result.objects.filter(roll_no__in=["R001", "R002", "R1000"])
.order_by("roll_no").values_list("roll_no", "score")))
print("total:", Result.objects.count())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): inserted: 1000 queries: 6 bulk_update rows: 2 [('R001', 99), ('R002', 57), ('R1000', 77)] total: 1001
Key points
- bulk_create batches inserts; bulk_update batches field updates
- update_conflicts=True gives an upsert
- Bulk methods skip save(), signals and validation
- Set batch_size for large data
- List auto_now fields explicitly in bulk_update
Common mistakes
- Expecting post_save signals or custom save() logic to run during bulk operations
- Passing huge lists to bulk_update without batch_size
- Forgetting updated_at in bulk_update's field list
- Using ignore_conflicts and then relying on primary keys being set
Follow-ups
- How would you import a 2 GB CSV file of attendance records?
- What SQL does bulk_update generate and why can it be slow?
- How do you report how many rows were inserted versus updated in an upsert?
Tips
- Quote a rough speed difference: thousands of queries versus a handful
- List exactly what bulk methods skip
- Describe a full import pipeline, not only the method call