Django 6.1.3

6.5 Models, metaclasses, and state

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:
    • 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 (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.
  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. This is the exact decision tree:

# 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 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:

Recorded on Django 6.1.3 ch06-models script
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:

Where Model.save leaks

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.