---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/db/models/query.py: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` (`django/db/models/sql/subqueries.py: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`** (`django/db/models/query.py: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` (`django/db/backends/base/operations.py:BaseDatabaseOperations.bulk_batch_size`, staying safely under SQLite's parameter limit) and, whenever `BaseDatabaseFeatures.can_return_rows_from_bulk_insert` (`django/db/backends/base/features.py:BaseDatabaseFeatures`) 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`** (`django/db/models/query.py: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:

```python
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:

```text recording=ch07-querysets
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`):

```text recording=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:
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` (`django/db/models/expressions.py:When`) branches inside a `Case` (`django/db/models/expressions.py: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

- **None of `update()`, `bulk_create()`, or `bulk_update()` calls `Model.save()`, `pre_save`, `post_save`, `full_clean()`, or `auto_now`.** If your model updates an `"updated_at"` timestamp via `auto_now=True` or invalidates a cache in `post_save`, bulk writes will silently skip both! (Update `"updated_at"` explicitly in `update(...)` / `bulk_update(..., ["note", "updated_at"])`.)
- **Calling `bulk_create` with `ignore_conflicts=True` or on MySQL leaves `Model.pk` as `None`.** Never pass those returned objects straight into a child table's `ForeignKey` without 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-first `CASE WHEN` matches.** Deduplicate `objs` by `pk` before calling `bulk_update` (Django evaluates `"WHEN"` branches in order, so the first branch for a duplicate `pk` wins 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/db/models/sql/`: the `Query` tree and `SQLCompiler`. We open that compiler next in [From Python to SQL](../sql.md).
