Updates, bulk_create, and cache invalidation
Why do QuerySet.update and QuerySet 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:
- Rejects sliced querysets, combined (
union/intersection) querysets, andQuerySetwith field names (.distinct TypeError/NotSupportedError). - Clones the internal
Queryinto anUpdateQuery, adds the update values (supportingFexpressions and subqueries!), clears the"SELECT"clause, and executes one SQL"UPDATE"insidetransaction..mark_for_rollback_on_error - Line 1447:
self. If you previously evaluated the queryset and cached its rows in._result_cache = None _result_cache, callingQuerySet.updateinvalidates_result_cacheimmediately 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 and QuerySet (lines 2171–2214):
- 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_createraisesValueErroron any multi-table child (including a proxy of a multi-table child!). - 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 theirAutoFieldcolumn is included in the"INSERT") from objects needing auto-generated PKs (where theAutoFieldcolumn is omitted so the database assigns it). If both buckets are non-empty, lines 893–894 wrap both inserts insidetransaction..atomic(savepoint=False) - Batching &
"RETURNING"primary keys:_batched_insertcomputes the safe batch size fromBaseDatabaseOperations(.bulk_batch_size BaseDatabaseOperations, staying safely under SQLite’s parameter limit) and, whenever.bulk_batch_size BaseDatabaseFeaturesis.can_return_rows_from_bulk_insert True(PostgreSQL, SQLite 3.35+, MariaDB 10.5+, Oracle — not MySQL!) andon_conflictisNoneorOnConflict, emits.UPDATE INSERT INTO ... VALUES (...), (...) RETURNING "id"and writes every newly assigned PK back onto each Python object (obj, lines 930–934)!._state .adding = False; obj ._state .db = self .db - Upserts via
"ignore_conflicts"and"update_conflicts": Passingignore_conflicts=Trueemits"ON CONFLICT DO NOTHING"(skipping"RETURNING"— PKs are not populated!). Passingupdate_conflicts=Truewithunique_fields=[...]andupdate_fields=[...]emits"ON CONFLICT (...) DO UPDATE SET ..."(OnConflict)..UPDATE
QuerySet.bulk_update : SQL CASE WHEN in one statement
Open QuerySet. 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 into bulk_batch_size so large updates split automatically across safe batches inside one transaction block!
Watch _result_cache invalidation, bulk_create’s "RETURNING" clause, and bulk_update’s exact "CASE WHEN" SQL run live on our newsroom app:
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):
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:
bulk_create(200)beats 200create()calls by5.9xeven on local in-memory SQLite (5.192 msvs30.483 ms) — and over a real 2 ms network RTT to PostgreSQL,200round-trips adds400+ msof pure network wait versus1round-trip!bulk_update(200)still pays Python expression-tree compilation cost (22.202 ms) for building 200Whenbranches inside aCasestatement — pass a reasonable"batch_size"(typically200–500) so SQL parsers do not choke on 10,000-branch"CASE"queries!- When every target row gets the same value or SQL expression,
QuerySet.updatewins by50x(0.620 ms) because it compiles zero per-row"CASE"branches.
Where bulk writes leak
- None of
update(),bulk_create(), orbulk_update()callsModel.save(),pre_save,post_save,full_clean(), orauto_now. If your model updates an"updated_at"timestamp viaauto_now=Trueor invalidates a cache inpost_save, bulk writes will silently skip both! (Update"updated_at"explicitly inupdate(...)/bulk_update(..., ["note", "updated_at"]).) - Calling
bulk_createwithignore_conflicts=Trueor on MySQL leavesModel.pkasNone. Never pass those returned objects straight into a child table’sForeignKeywithout re-querying their assigned PKs if the backend cannot return rows from bulk insert. - Duplicate primary keys inside
bulk_update(objs, ...)trigger unpredictable last-or-firstCASE WHENmatches. Deduplicateobjsbypkbefore callingbulk_update(Django evaluates"WHEN"branches in order, so the first branch for a duplicatepkwins silently!).
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/: the Query tree and SQLCompiler. We open that compiler next in From Python to SQL.