Add upsert() and remove update_or_create() #88
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #88"
general
weight: 0.35
davegaeddert
Summary
Adds single-row
QuerySet.upsert()and removesupdate_or_create()outright, migrating all internal callers. Based on master, now that #85 and #86 have landed.One
INSERT ... ON CONFLICT (unique_fields) DO UPDATE SET ... RETURNING <cols>, (xmax = 0)statement — no transaction wrapper, nothing to retry. Returns(obj, created)withobjhydrated from the post-write row (no second query);createdcomes from the(xmax = 0)flag (freshly-inserted tuples havexmax = 0).How it works
dialect.returning_columns(fields, include_created=True)appends(xmax = 0)to the RETURNING clause, so the trick and the comment explaining it live in the postgres SQL-text layer withbulk_insert_sql/on_conflict_suffix_sql. Converters only run on the real field columns;upsert()pops the trailing bool.meta.fieldsin declaration order (so the emitted SQL is stable across processes), theSETclause covers every non-unique, non-PK column named inkwargs/defaults→EXCLUDED.col, plus everyDateTimeField(update_now=True)column —pre_save()already stamped a fresh value into the INSERT, soEXCLUDEDcarries it and dropping it would let the timestamp go stale. Acreate_now-only column stays out and keeps its original value.create_defaultsare insert-only and never in theSET.SQLInsertCompiler._conflict_assignmentsbuilds the wholeDO UPDATE SETlist — SQL fragments and their parameters — in one loop in one order, anddialect.on_conflict_suffix_sqlis a pure formatter over already-ordered(quoted column, value SQL)pairs. That single-pass shape is load-bearing: the two used to be built separately, in different orders, and bound each value to the wrong column. Each override compiles through the sharedSQLCompiler._compile_assignment_value— the same helperUPDATE ... SETuses — so a value can be plain, a related instance, or an expression. Overrides replace a column already in theSETand append one that isn't. When every inserted column is a unique field there's nothing to set, so a unique column is set to itself as a no-op —DO UPDATE(notDO NOTHING) is required for RETURNING to return the conflicting row.Excluded(): a conflict update sees two rows, andF()only reached one of them.F("count")reads the row already stored; the newExcluded("count")reads the row the INSERT proposed, compiling toEXCLUDED."count". Combining them accumulates rather than overwrites —F("count") + Excluded("count")adds this call's delta to whatever is there, in one statement. Exported fromplain.postgresnext toF.EXCLUDEDexists only insideON CONFLICT DO UPDATE, soresolve_expressionrefuses every other compile context (filter(),update(),annotate(), a plain insert) with aFieldErrorrather than emitting SQL Postgres would reject with a worse message.create_now,generate=True,RandomStringField) can't be named inkwargs/defaults—EXCLUDEDcarries a freshly evaluated default, so the conflict update would reset a creation timestamp every time. Mirrors the rulebulk_upsertenforces onupdate_fields. A column that's alsoupdate_nowis exempt, since refreshing it is the point.unique_fieldstake typed field references (Model.key, not"key") and must match a totalUniqueConstraint— not the PK, since Postgres generates the identity value and a caller has nothing to conflict on. A foreign key is named asModel.fk, which is the relation descriptor rather than the column, so_validate_field_refsresolves it —unique_fields=[Order.customer, Order.number]works againstUniqueConstraint(fields=["customer", "number"]), and the element type isSequence[Field[Any] | type[Model]], the same asbulk_upsert— both call one_validate_upsert_unique_columns, and one_reject_database_owned_update, rather than keeping two spellings of each rule. Unique values must be non-null. Unknown keys inkwargs/defaultsraise a cleanFieldErrorvia_validate_model_field_names;conflict_defaultsmust name a real column — a many-to-many field passes the name lookup but has none — may not name a unique field, which would rewrite the conflict target it just matched on, and is held to the same column rules as the derived update set (no primary key, no database-owned column). Every source resolves callables, and a settable property is refused outright: theSETclause is derived from columns, so a property could only ever be written on the insert half. An expression (F(),Upper(),Excluded(), or a callable returning one) is refused as an inserted value inkwargs/defaults/create_defaults— an expression is computed from a row and the insert has no row to compute from, so the field would coerce the object itself and a text column would store its repr. Expressions belong inconflict_defaults. Nofull_cleanof the merged row (consistent with the bulk paths), so a constraint violation surfaces as a rawpsycopg.IntegrityError.Semantics worth reviewing
Two deliberate departures from
update_or_create:create_defaultsis an additive insert-only layer, not Django's replacement fordefaults. Precedence iscreate_defaults<defaults<kwargs.kwargsare values, not filters.update_or_create's kwargs were the lookup;upsert's are columns written to whichever row conflicts.unique_fieldsalone decides which row that is — which is why it has to match a real total unique constraint.Known limits
upsert()ignores the queryset's filters.qs.filter(...).upsert(...)writes the conflicting row whether or not it matches the filter — the conflict constraint decides which row is touched. It isn't guarded because the related-manager wrappers upsert through a filtered queryset by design. Documented in the docstring and README, and pinned by a test.add()has a pre-existing TOCTOU. It reads the missing target ids and then inserts, and the through model carries no unique constraint, so two concurrent callers can duplicate a through-row. Pre-existing inadd(); this PR puts it on everyupsert()/get_or_create()path by callingadd()unconditionally. Tracked separately.Excluded()'s compile-context flag is per-compiler.* Forcing a re-entry into the same compiler while it is building conflict assignments would clear the outer flag on the way out. No public route to that exists —_conflict_assignmentsis the only writer and it doesn't recurse — so this is a note, not a hole.unique_fieldsand that a string is rejected. TheExcluded()-as-inserted-value andconflict_defaultskey checks stay runtime-only: those parameters areAny(kwargs,dict[str, Any]), so there is nothing for a checker to reject.Caller migrations
plain-flags,plain-sessions→upsert(), each dropping from 2+ queries to 1.update_or_create→upsert. The M2M wrapper now adds the through-row unconditionally rather than only on insert: theget()/conflict runs against the unscopedself.model.query, so an existing-but-unrelated target came backcreated=Falseand the relationship was never made.add()skips through-rows that already exist. The same one-line fix applies to the M2Mget_or_create()sibling, which had the bug latent.Upgrade
update_or_create()is gone; there is no shim.update_or_create(lookup, defaults=...)becomesupsert(lookup, defaults=..., unique_fields=[Model.field, ...]).defaults=andcreate_defaults=keep their names butcreate_defaultsno longer replacesdefaults— it layers under it. The non-mechanical part is several-fold.upsertrequires the lookup to be a declared unconditionalUniqueConstraint(or PK-free equivalent), whichupdate_or_createdid not — a call keyed on a non-unique column has no direct translation and needs a real constraint or aget/createpair. Andupsert()targets the conflict constraint, never the queryset's filters: aqs.filter(...).update_or_create(...)caller was scoped by that filter and anupsert()is not, so the filter has to be folded into the conflict key (and the constraint), or replaced by a locked read plus write.Four more things a rewrite has to account for:
unique_fieldsneeds a declared unconditionalUniqueConstraint, and adding one to a populated table means deduplicating the existing rows first — a data migration, not just a schema change.update_or_create(key=..., value=999, defaults=...)looked up on both columns and failed loudly ifvaluedidn't match;upsert(key=..., value=999, defaults=..., unique_fields=[Model.key])writesvalue=999over whatever is stored.kwargsare values, not filters — any lookup column that isn't in the conflict key is now an overwrite.update_or_create(defaults={"count": F("count") + 1})was legal because the update went through the instance.upsert()inserts and updates in one statement, so an expression has to move toconflict_defaults— whereExcluded()also becomes available.obj.children.update_or_create(...)→obj.children.upsert(..., unique_fields=[...])on both the reverse-FK and many-to-many managers. Separately,ManyToManyManager.get_or_create()now relates a pre-existing but unrelated target instead of silently leaving it unrelated — a behavior change, and a bug fix.Tests
test_upsert.py, 66 tests — insert/conflict, defaults, create_defaults insert-only, callable resolution (including that a shadowed callable never runs), the F-counter, a related-instance override,update_nowrefresh withcreate_nowpreserved, unique-only idempotency, ignored queryset filters, single-statement counts, and the validation errors: string/wrong-model/PK unique fields, unknown names, null keys, settable properties in any source, expressions as inserted values,conflict_defaultsnaming a unique field / a many-to-many field / the primary key / a database-owned column, anddefaultspassed positionally.Excluded()is covered by the emitted SQL, the accumulate-vs-overwrite result, the misuse errors, and a real concurrency test: the statementupsert()actually emits is captured and then replayed from eight sessions at once, asserting no increment is lost. It uses raw connections because the test harness scopes its database to the main thread, so the racing sessions can't go through the ORM.Parameter binding is pinned two ways: an end-to-end test declaring two overrides of different types in the opposite of model order and asserting the stored row, plus a SQL-shape test asserting the
SETorder matches the parameter order. A foreign key in the conflict target is covered end to end onUpsertScoped— insert/conflict, scoping by parent, and the parent-plus-key case through the reverse manager — with the union pinned statically intests/typing/upsert_writes.py.UpsertStampedis the one fixture this PR adds: the timestamp columns nobody names, plus the non-key foreign key a related-instanceconflict_defaultneeds.Plus M2M/FK manager relationship tests (
test_m2m.py, 11) and a plain-flags test pinning the timestamp refresh through the real caller.plain-postgresis 1284 passed / 5 skipped; the full suite is 27 packages green, and./scripts/fixand./scripts/type-check .are clean. (plain-dev'stest_nested_app_directories_do_not_collide_across_worktreesis deselected locally — it scrubsGIT_from its environment, which strips the commit-signing override and trips a locked signing agent. It is untouched by this PR.)