← Back to Django, page 3

django-0045 · Hard senior

How do bulk_create, bulk_update and upserts work in Django, and what do they skip compared with save()?

bulk_create() inserts many objects in few queries, bulk_update() updates chosen fields for many objects, and bulk_create(update_conflicts=True, unique_fields=..., update_fields=...) performs an upsert (INSERT ... ON CONFLICT DO UPDATE) on PostgreSQL, SQLite and MariaDB/MySQL. They are much faster than looping over save(), but they do not call save(), do not send pre_save/post_save signals and do not run model validation, so add those steps yourself if needed.

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=True skips 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 ... END per batch. Large batches create very long SQL, so set batch_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_save signals.
  • full_clean() validation. Database constraints still apply.
  • auto_now fields are set by bulk_create but bulk_update only updates fields you list, so include updated_at explicitly and set it yourself.

Good import pattern:

  1. Read and validate input in Python (a form or serializer per row, or a vectorised check).
  2. Upsert in batches inside transaction.atomic() per batch.
  3. Report rows inserted, updated and rejected.
  4. Trigger side effects (cache clear, notifications) once after the batch, not per row.
python
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