← Back to Pull requests

Add upsert() and remove update_or_create() #88

Closed
unknown closed this pull request without merging on Sep 20, 2026 03:25 UTC
View on GitHub
unknown unknown commented on Jul 23, 2026 17:15 UTC
Author

Summary

Adds single-row QuerySet.upsert() and removes update_or_create() outright, migrating all internal callers. Based on master, now that #85 and #86 have landed.

obj, created = Model.query.upsert(
    key="my-key",
    defaults={"value": data},                     # insert and conflict-update
    create_defaults={"source": "x"},              # insert only
    conflict_defaults={"count": F("count") + 1},  # conflict-update only
    unique_fields=[Model.key],
)

One INSERT ... ON CONFLICT (unique_fields) DO UPDATE SET ... RETURNING <cols>, (xmax = 0) statement — no transaction wrapper, nothing to retry. Returns (obj, created) with obj hydrated from the post-write row (no second query); created comes from the (xmax = 0) flag (freshly-inserted tuples have xmax = 0).

How it works

  • created flag: 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 with bulk_insert_sql/on_conflict_suffix_sql. Converters only run on the real field columns; upsert() pops the trailing bool.

  • SET columns: derived, not passed. Walking meta.fields in declaration order (so the emitted SQL is stable across processes), the SET clause covers every non-unique, non-PK column named in kwargs/defaults → EXCLUDED.col, plus every DateTimeField(update_now=True) column — pre_save() already stamped a fresh value into the INSERT, so EXCLUDED carries it and dropping it would let the timestamp go stale. A create_now-only column stays out and keeps its original value. create_defaults are insert-only and never in the SET.

  • conflict_defaults: SQLInsertCompiler._conflict_assignments builds the whole DO UPDATE SET list — SQL fragments and their parameters — in one loop in one order, and dialect.on_conflict_suffix_sql is 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 shared SQLCompiler._compile_assignment_value — the same helper UPDATE ... SET uses — so a value can be plain, a related instance, or an expression. Overrides replace a column already in the SET and 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 (not DO NOTHING) is required for RETURNING to return the conflicting row.

  • Excluded(): a conflict update sees two rows, and F() only reached one of them. F("count") reads the row already stored; the new Excluded("count") reads the row the INSERT proposed, compiling to EXCLUDED."count". Combining them accumulates rather than overwrites — F("count") + Excluded("count") adds this call's delta to whatever is there, in one statement. Exported from plain.postgres next to F. EXCLUDED exists only inside ON CONFLICT DO UPDATE, so resolve_expression refuses every other compile context (filter(), update(), annotate(), a plain insert) with a FieldError rather than emitting SQL Postgres would reject with a worse message.

  • Database-owned columns (create_now, generate=True, RandomStringField) can't be named in kwargs/defaults — EXCLUDED carries a freshly evaluated default, so the conflict update would reset a creation timestamp every time. Mirrors the rule bulk_upsert enforces on update_fields. A column that's also update_now is exempt, since refreshing it is the point.

  • Validation (all before the query): unique_fields take typed field references (Model.key, not "key") and must match a total UniqueConstraint — not the PK, since Postgres generates the identity value and a caller has nothing to conflict on. A foreign key is named as Model.fk, which is the relation descriptor rather than the column, so _validate_field_refs resolves it — unique_fields=[Order.customer, Order.number] works against UniqueConstraint(fields=["customer", "number"]), and the element type is Sequence[Field[Any] | type[Model]], the same as bulk_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 in kwargs/defaults raise a clean FieldError via _validate_model_field_names; conflict_defaults must 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: the SET clause 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 in kwargs/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 in conflict_defaults. No full_clean of the merged row (consistent with the bulk paths), so a constraint violation surfaces as a raw psycopg.IntegrityError.
  • Semantics worth reviewing

    Two deliberate departures from update_or_create:

  • create_defaults is an additive insert-only layer, not Django's replacement for defaults. Precedence is create_defaults < defaults < kwargs.

  • kwargs are values, not filters. update_or_create's kwargs were the lookup; upsert's are columns written to whichever row conflicts. unique_fields alone 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.

  • The M2M manager's 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 in add(); this PR puts it on every upsert()/get_or_create() path by calling add() 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_assignments is the only writer and it doesn't recurse — so this is a note, not a hole.

  • The typing corpus can only pin part of the surface. It asserts that a foreign key and a plain column are both accepted in unique_fields and that a string is rejected. The Excluded()-as-inserted-value and conflict_defaults key checks stay runtime-only: those parameters are Any (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.

  • FK reverse manager and M2M manager update_or_create → upsert. The M2M wrapper now adds the through-row unconditionally rather than only on insert: the get()/conflict runs against the unscoped self.model.query, so an existing-but-unrelated target came back created=False and the relationship was never made. add() skips through-rows that already exist. The same one-line fix applies to the M2M get_or_create() sibling, which had the bug latent.
  • Upgrade

    update_or_create() is gone; there is no shim. update_or_create(lookup, defaults=...) becomes upsert(lookup, defaults=..., unique_fields=[Model.field, ...]). defaults= and create_defaults= keep their names but create_defaults no longer replaces defaults — it layers under it. The non-mechanical part is several-fold. upsert requires the lookup to be a declared unconditional UniqueConstraint (or PK-free equivalent), which update_or_create did not — a call keyed on a non-unique column has no direct translation and needs a real constraint or a get/create pair. And upsert() targets the conflict constraint, never the queryset's filters: a qs.filter(...).update_or_create(...) caller was scoped by that filter and an upsert() 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:

  • Adding the constraint is real work. unique_fields needs a declared unconditional UniqueConstraint, and adding one to a populated table means deduplicating the existing rows first — a data migration, not just a schema change.

  • A wider lookup silently changes meaning. update_or_create(key=..., value=999, defaults=...) looked up on both columns and failed loudly if value didn't match; upsert(key=..., value=999, defaults=..., unique_fields=[Model.key]) writes value=999 over whatever is stored. kwargs are values, not filters — any lookup column that isn't in the conflict key is now an overwrite.

  • Expressions move. 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 to conflict_defaults — where Excluded() also becomes available.

  • Related managers renamed. 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_now refresh with create_now preserved, 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_defaults naming a unique field / a many-to-many field / the primary key / a database-owned column, and defaults passed positionally.

    Excluded() is covered by the emitted SQL, the accumulate-vs-overwrite result, the misuse errors, and a real concurrency test: the statement upsert() 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 SET order matches the parameter order. A foreign key in the conflict target is covered end to end on UpsertScoped — insert/conflict, scoping by parent, and the parent-plus-key case through the reverse manager — with the union pinned statically in tests/typing/upsert_writes.py. UpsertStamped is the one fixture this PR adds: the timestamp columns nobody names, plus the non-key foreign key a related-instance conflict_default needs.

    Plus M2M/FK manager relationship tests (test_m2m.py, 11) and a plain-flags test pinning the timestamp refresh through the real caller.

    plain-postgres is 1284 passed / 5 skipped; the full suite is 27 packages green, and ./scripts/fix and ./scripts/type-check . are clean. (plain-dev's test_nested_app_directories_do_not_collide_across_worktrees is deselected locally — it scrubs GIT_ from its environment, which strips the commit-signing override and trips a locked signing agent. It is untouched by this PR.)

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: davegaeddert Review duration: 84129m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository