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

# Inside Model.save: insert vs. update

How does `Model.save` decide between INSERT and UPDATE, why can saving an object with a preset primary key run two queries, and how does `update_fields` avoid lost updates?

Calling `"desk.save()"` looks atomic and obvious: insert a new row, or update an existing one. Yet SQL has no universal single-statement `"UPSERT"` that fits every database backend and Django signal contract. Open `django/db/models/base.py` lines 841–1269 and you find a careful three-layer pipeline — `Model.save` → **`Model.save_base`** → `Model._save_table` — packed with subtle branches that directly affect both SQL query count and concurrency safety.

## From `Model.save` into `Model.save_base`

Follow the call stack line by line:

1. **`Model.save`** (`django/db/models/base.py:Model.save`):
   - Calls `Model._prepare_related_fields_for_save` (lines 1270–1323), which checks every cached `ForeignKey` / `OneToOneField` and raises `ValueError("save() prohibited to prevent data loss due to unsaved related object ...")` if you assigned an unsaved related instance (`pk is None`)!
   - Validates that `"force_insert"` is not combined with `"force_update"` or **`update_fields`** (`ValueError`), and checks every name in `update_fields` against `Options._non_pk_concrete_field_names` (`django/db/models/options.py:Options`, rejecting primary keys, many-to-many fields, and non-concrete fields).
   - **Automatic deferred narrowing (lines 889–902):** If the instance was loaded with `QuerySet.only` or `QuerySet.defer`, `update_fields` was *not* explicitly passed, `pk` is set, and you are saving back to the same database (`using == self._state.db`), Django **automatically constructs `update_fields` from the loaded concrete fields**! That prevents `save()` from firing extra `"SELECT"` queries to fetch deferred fields just to write them back unchanged.
   - Delegates to **`Model.save_base`** (`django/db/models/base.py:Model.save_base`).
2. **`Model.save_base`** (lines 950–1019):
   - Resolves proxy models down to `cls = cls._meta.concrete_model` (while keeping `sender=origin` for `pre_save` / `post_save` signals!).
   - Fires `pre_save`.
   - Wraps multi-table parent saves (`if meta.parents:`) in `transaction.atomic(using=using, savepoint=False)` so parent and child inserts either succeed or roll back together; single-table models avoid transaction overhead and use `transaction.mark_for_rollback_on_error`.
   - Calls `Model._save_parents` (for multi-table inheritance) and then `Model._save_table`.
   - Flips `self._state.db = using` and `self._state.adding = False`, then fires `post_save(..., created=(not updated))`.

## How `Model._save_table` decides `"INSERT"` vs. `"UPDATE"` (and the preset-PK 2-query trap!)

Open `Model._save_table` (`django/db/models/base.py:Model._save_table`). This is the exact decision tree:

```python
# Skip an UPDATE when adding an instance and primary key has a default.
if (
    not raw
    and not force_insert
    and not force_update
    and self._state.adding
    and all(f.has_default() or f.has_db_default() for f in meta.pk_fields)
):
    force_insert = True
# If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
if pk_set and not force_insert:
    ...
    results = self._do_update(...)
    if updated := bool(results):
        self._assign_returned_values(results[0], returning_fields)
    elif force_update:
        raise self.NotUpdated("Forced update did not affect any rows.")
    elif update_fields:
        raise self.NotUpdated("Save with update_fields did not affect any rows.")
if not updated:
    ...
    results = self._do_insert(...)
```

Read those lines carefully — they explain four crucial runtime behaviors at once:

1. **Brand-new model with auto PK (`pk is None`):** `"pk_set"` is `False`, so Django skips `_do_update` completely and runs a single `"INSERT"` (using `RETURNING "id"` on SQLite/PostgreSQL to populate `Model.pk` in one round-trip!).
2. **Brand-new model with a defaulted PK (e.g. `django.db.models.UUIDField`, `primary_key=True, default=uuid.uuid4`):** Even though `"pk_set"` is `True` before `save()`, lines 1107–1114 see `self._state.adding is True` *and* every primary-key field reports `Field.has_default` (`django/db/models/fields/__init__.py:Field.has_default`) or `Field.has_db_default`, so Django flips `force_insert = True` and runs a single `"INSERT"`.
3. **The preset-PK two-query trap:** Now instantiate a model with an explicit primary key on an `AutoField` / `BigAutoField` (which has *no* Python or DB default!) — e.g. `"Desk(id=9999, name=..., slug=..., section_code=...).save()"`. Because `"pk_set"` is `True` and `has_default()` is `False`, Django does **not** set `force_insert = True`: it first executes **`UPDATE "newsroom_desk" SET ... WHERE "id" = 9999`**, gets `0` affected rows back from the database, and *only then* executes **`INSERT INTO "newsroom_desk" ...`**! Passing `force_insert=True` cuts that directly back down to **1 query**.
4. **Django `6.1`'s `"NotUpdated"`:** When `force_update=True` or `update_fields=[...]` updates `0` rows (for example, another request deleted the row in the meantime), lines 1153–1158 now raise the model's synthesized **`"NotUpdated"`** exception (a subclass of both `ObjectNotUpdated` and `DatabaseError`) instead of silently falling through to `"INSERT"`!

Watch all seven save paths execute live on our newsroom `"Desk"` model:

```text recording=ch06-models
Model.save(): INSERT, UPDATE, preset PK 2-query trap, and update_fields
  new Desk().save() -> queries=1 ops=['INSERT'] adding=False
  loaded desk.save() -> queries=1 ops=['UPDATE'] sql=UPDATE "newsroom_desk" SET "name" = %s, "slug" = %s, "section_code" = %s WHERE "newsroom_desk"."id" = %s
  preset Desk(id=9999).save() -> queries=2 ops=['UPDATE', 'INSERT'] (UPDATE 0 rows, then INSERT!)
  preset Desk(id=9998).save(force_insert=True) -> queries=1 ops=['INSERT']
  save(update_fields=['section_code']) -> queries=1 sql=UPDATE "newsroom_desk" SET "section_code" = %s WHERE "newsroom_desk"."id" = %s
  .only('section_code') auto update_fields -> queries=1 sql=UPDATE "newsroom_desk" SET "section_code" = %s WHERE "newsroom_desk"."id" = %s
  save(force_update=True) missing row -> Desk.NotUpdated (is DatabaseError=True): Forced update did not affect any rows.
```

## Why `update_fields` prevents lost updates

Compare line 45 and line 48 in the recording above:
- Plain `"desk.save()"` emits **`SET "name" = %s, "slug" = %s, "section_code" = %s`** — rewriting **every** concrete column on the table with whatever stale values happen to sit in this Python instance! If request A loads `"desk"`, changes `"name"`, and saves while request B loads `"desk"`, changes `"section_code"`, and calls plain `"desk.save()"`, request B **silently clobbers request A's `"name"` change** back to its old value (a classic lost update).
- Calling `"desk.save(update_fields=['section_code'])"` emits **`SET "section_code" = %s`** — touching only the single column request B modified, leaving request A's `"name"` edit intact! (And for numeric counters like view counts, pair `F` expressions — Chapter 8 — with `update_fields` or `QuerySet.update` so the database computes the increment atomically.)

## Where `Model.save` leaks

- **Plain `save()` overwrites untouched columns under concurrency.** Defaulting to `save(update_fields=[...])` whenever a view or background task modifies specific columns eliminates whole classes of lost-update bugs and reduces write amplification on wide tables with big `TextField` / `django.db.models.JSONField` blobs.
- **Fields with `auto_now=True` are skipped unless included in `update_fields`.** Because `django.db.models.DateTimeField.pre_save` only runs for fields inside the filtered `"non_pks_non_generated"` list, passing `update_fields=["status"]` will **not** bump an `"updated_at"` (`auto_now=True`) timestamp unless `"updated_at"` is also listed in `update_fields`!
- **`QuerySet.update` bypasses `Model.save`, `pre_save`, `post_save`, and `auto_now`.** When you call `"Story.objects.filter(...).update(status='published')"`, Django builds a SQL `UpdateQuery` directly without loading Python instances or invoking custom `save()` overrides.
- **Saving an instance loaded with `F()` expressions leaves an `F` object unless the backend supports `"RETURNING"`.** Notice lines 1137–1141 and 1261–1268 of `base.py`: on backends that support `UPDATE ... RETURNING` (SQLite 3.35+, PostgreSQL), Django refreshes expression-assigned fields automatically via `_assign_returned_values`; on backends without it (like MySQL), Django pops the stale attribute out of `__dict__` so the next read triggers a fresh `"SELECT"`.

Inserting and updating touch one row (or one inheritance chain). Deleting a row is far trickier — because a single row can be referenced by tables across every app in your project. We open Django's deletion engine next in [Collector, cascades, and fast deletes](deleting.md).
