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/ lines 841–1269 and you find a careful three-layer pipeline — Model.save → Model.save_base → Model — 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:
Model.save:- Calls
Model(lines 1270–1323), which checks every cached._prepare_related_fields_for_save ForeignKey/OneToOneFieldand raisesValueError("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"orupdate_fields(ValueError), and checks every name inupdate_fieldsagainstOptions(._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.onlyorQuerySet.defer,update_fieldswas not explicitly passed,pkis set, and you are saving back to the same database (using == self), Django automatically constructs._state .db update_fieldsfrom the loaded concrete fields! That preventssave()from firing extra"SELECT"queries to fetch deferred fields just to write them back unchanged. - Delegates to
Model.save_base.
- Calls
Model.save_base(lines 950–1019):- Resolves proxy models down to
cls = cls(while keeping._meta .concrete_model sender=originforpre_save/post_savesignals!). - Fires
pre_save. - Wraps multi-table parent saves (
if meta.parents:) intransactionso parent and child inserts either succeed or roll back together; single-table models avoid transaction overhead and use.atomic(using=using, savepoint=False) transaction..mark_for_rollback_on_error - Calls
Model(for multi-table inheritance) and then._save_parents Model.._save_table - Flips
selfand._state .db = using self, then fires._state .adding = False post_save(..., created=(not updated)).
- Resolves proxy models down to
How Model._save_table decides "INSERT" vs. "UPDATE" (and the preset-PK 2-query trap!)
Open Model. 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:
- Brand-new model with auto PK (
pk is None):"pk_set"isFalse, so Django skips_do_updatecompletely and runs a single"INSERT"(usingRETURNING "id"on SQLite/PostgreSQL to populateModel.pkin one round-trip!). - Brand-new model with a defaulted PK (e.g.
django,.db .models .UUIDField primary_key=True, default=uuid): Even though.uuid4 "pk_set"isTruebeforesave(), lines 1107–1114 seeselfand every primary-key field reports._state .adding is True Fieldor.has_default Field, so Django flips.has_db_default force_insert = Trueand runs a single"INSERT". - 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"isTrueandhas_default()isFalse, Django does not setforce_insert = True: it first executesUPDATE "newsroom_desk" SET ... WHERE "id" = 9999, gets0affected rows back from the database, and only then executesINSERT INTO "newsroom_desk" ...! Passingforce_insert=Truecuts that directly back down to 1 query. - Django
6.1’s"NotUpdated": Whenforce_update=Trueorupdate_fields=[...]updates0rows (for example, another request deleted the row in the meantime), lines 1153–1158 now raise the model’s synthesized"NotUpdated"exception (a subclass of bothObjectNotUpdatedandDatabaseError) instead of silently falling through to"INSERT"!
Watch all seven save paths execute live on our newsroom "Desk" model:
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()"emitsSET "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
"deskemits.save(update_fields=['section_code'])" 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, pairFexpressions — Chapter 8 — withupdate_fieldsorQuerySet.updateso the database computes the increment atomically.)
Where Model.save leaks
- Plain
save()overwrites untouched columns under concurrency. Defaulting tosave(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 bigTextField/djangoblobs..db .models .JSONField - Fields with
auto_now=Trueare skipped unless included inupdate_fields. Becausedjangoonly runs for fields inside the filtered.db .models .DateTimeField .pre_save "non_pks_non_generated"list, passingupdate_fields=["status"]will not bump an"updated_at"(auto_now=True) timestamp unless"updated_at"is also listed inupdate_fields! QuerySet.updatebypassesModel.save,pre_save,post_save, andauto_now. When you call"Story, Django builds a SQL.objects .filter(...).update(status='published')" UpdateQuerydirectly without loading Python instances or invoking customsave()overrides.- Saving an instance loaded with
F()expressions leaves anFobject unless the backend supports"RETURNING". Notice lines 1137–1141 and 1261–1268 ofbase.py: on backends that supportUPDATE ... 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.