Django 6.1.3

7.7 QuerySets and laziness

Updates, bulk_create, and cache invalidation

Why do QuerySet.update and QuerySet.bulk_create bypass Model.save and signals, and what happens to _result_cache and auto-generated primary keys?

When a newsroom job needs to insert 200 corrections or flip the priority on 10,000 stories, calling Model.save in a Python loop executes 200 (or 10,000) separate SQL round-trips, fires pre_save and post_save on every single object, and runs Python field preparation one row at a time. QuerySet provides three direct SQL write verbs — QuerySet.update, bulk_create, and bulk_update — that bypass Model.save completely in exchange for single-statement (or batched) SQL throughput.

QuerySet.update: direct SQL and _result_cache = None

Open QuerySet.update:

  1. Rejects sliced querysets, combined (union/intersection) querysets, and QuerySet.distinct with field names (TypeError / NotSupportedError).
  2. Clones the internal Query into an UpdateQuery, adds the update values (supporting F expressions and subqueries!), clears the "SELECT" clause, and executes one SQL "UPDATE" inside transaction.mark_for_rollback_on_error.
  3. Line 1447: self._result_cache = None. If you previously evaluated the queryset and cached its rows in _result_cache, calling QuerySet.update invalidates _result_cache immediately so the next iteration re-fetches the updated database rows instead of handing back stale objects. (Note: other already-loaded Python instances pointing to those same rows are not refreshed — Django has no identity map!)

QuerySet.bulk_create: splitting PKs, batching, and "RETURNING"

Open QuerySet.bulk_create and QuerySet._batched_insert (lines 2171–2214):

  1. Rejects multi-table inherited models (lines 869–871): Because multi-table inheritance requires inserting into parent tables first to obtain parent PKs before inserting into the child table, bulk_create raises ValueError on any multi-table child (including a proxy of a multi-table child!).
  2. Splits rows with and without PKs (_prepare_for_bulk_create, lines 763–777): Runs _prepare_related_fields_for_save (catching unsaved FK instances!) and separates objects that already have a PK (so their AutoField column is included in the "INSERT") from objects needing auto-generated PKs (where the AutoField column is omitted so the database assigns it). If both buckets are non-empty, lines 893–894 wrap both inserts inside transaction.atomic(savepoint=False).
  3. Batching & "RETURNING" primary keys: _batched_insert computes the safe batch size from BaseDatabaseOperations.bulk_batch_size (BaseDatabaseOperations.bulk_batch_size, staying safely under SQLite’s parameter limit) and, whenever BaseDatabaseFeatures.can_return_rows_from_bulk_insert is True (PostgreSQL, SQLite 3.35+, MariaDB 10.5+, Oracle — not MySQL!) and on_conflict is None or OnConflict.UPDATE, emits INSERT INTO ... VALUES (...), (...) RETURNING "id" and writes every newly assigned PK back onto each Python object (obj._state.adding = False; obj._state.db = self.db, lines 930–934)!
  4. Upserts via "ignore_conflicts" and "update_conflicts": Passing ignore_conflicts=True emits "ON CONFLICT DO NOTHING" (skipping "RETURNING" — PKs are not populated!). Passing update_conflicts=True with unique_fields=[...] and update_fields=[...] emits "ON CONFLICT (...) DO UPDATE SET ..." (OnConflict.UPDATE).

QuerySet.bulk_update: SQL CASE WHEN in one statement

Open QuerySet.bulk_update. Unlike QuerySet.update (which assigns one value or expression to every matched row), bulk_update lets every row receive a different value in a single "UPDATE" per batch by generating SQL "CASE WHEN" expressions:

for field in fields:
    when_statements = [When(pk=obj.pk, then=Value(getattr(obj, field.attname), ...)) for obj in batch_objs]
    update_kwargs[field.attname] = Case(*when_statements, output_field=field)

Notice lines 1021–1024: because every object uses its primary key twice (once inside When(pk=...) and once inside WHERE id IN (...)), Django passes [opts.pk, opts.pk, *fields] into bulk_batch_size so large updates split automatically across safe batches inside one transaction.atomic(savepoint=False) block!

Watch _result_cache invalidation, bulk_create’s "RETURNING" clause, and bulk_update’s exact "CASE WHEN" SQL run live on our newsroom app:

Recorded on Django 6.1.3 ch07-querysets script
Bulk writes: update(), bulk_create(), bulk_update(), and _result_cache
  qs.update(priority=1) -> rows=1 queries=1 cache_before=True cache_after=None
  bulk_create(3) -> queries=1 all_pks_populated=True has_RETURNING=True
  bulk_update(3, ['note']) -> rows=3 has_CASE_WHEN=True
    bulk_update SQL: UPDATE "newsroom_correction" SET "note" = CASE WHEN ("newsroom_correction"."id" = %s) THEN %s WHEN ("newsroom_correction"."id" = %s) THEN %s WHEN ("newsroom_correction"."id" = %s) THEN %s ELSE NULL END WHERE "newsroom_correction"."id" IN (%s, %s, %s)

And compare the real wall-clock cost across 200 "Correction" rows (ch07-bench):

Recorded on Django 6.1.3 ch07-bench script
Bulk writes vs per-row loops across 200 Correction rows (5 trials)
  operation                                    sql_queries  median_ms
  200x Correction.objects.create() [loop]              200     30.483
  Correction.objects.bulk_create(200)                    1      5.192
  200x obj.save(update_fields=['note'])                200     30.930
  Correction.objects.bulk_update(200)                    1     22.202
  QuerySet.update() [uniform value]                      1      0.620

Look closely at those three takeaways:

  1. bulk_create(200) beats 200 create() calls by 5.9x even on local in-memory SQLite (5.192 ms vs 30.483 ms) — and over a real 2 ms network RTT to PostgreSQL, 200 round-trips adds 400+ ms of pure network wait versus 1 round-trip!
  2. bulk_update(200) still pays Python expression-tree compilation cost (22.202 ms) for building 200 When branches inside a Case statement — pass a reasonable "batch_size" (typically 200–500) so SQL parsers do not choke on 10,000-branch "CASE" queries!
  3. When every target row gets the same value or SQL expression, QuerySet.update wins by 50x (0.620 ms) because it compiles zero per-row "CASE" branches.

Where bulk writes leak

Every QuerySet method we traced in this chapter — filter(), select_related(), annotate(), update(), bulk_update() — hands off all actual SQL construction to two deeper layers inside django/db/models/sql/: the Query tree and SQLCompiler. We open that compiler next in From Python to SQL.