TL;DR

  • Django's get_or_create() handles concurrent inserts. It looks up the row, attempts an atomic insert on a miss, and retries the lookup after IntegrityError, if a database-enforced unique constraint matches the lookup arguments. It returns a hydrated model instance and a built-in created boolean.
  • PostgreSQL 19 collapses the recovery branch. INSERT ... ON CONFLICT DO SELECT ... RETURNING inserts or returns the conflicting row in one statement, closing a Read Committed visibility gap that traps older CTE workarounds. It returns row values, not a model instance. A created indicator comes from OLD.id IS NULL, not a built-in flag.
  • Adopt narrowly, test first. Keep get_or_create() when the model lifecycle and object contract matter. Use a narrow cursor.execute() wrapper when most calls insert new rows or contend with concurrent inserters, so the native statement removes the recovery branch. When most calls retrieve existing rows, get_or_create() finishes in one SELECT without entering the insert path. Test concurrent commits, rollbacks, and transaction retries before widening use.

Two concurrent requests for the same unique tag can both miss the initial read and attempt an insert. If the first insert remains uncommitted when the second reaches the unique constraint, the second waits. If the first transaction commits, the second insert raises an IntegrityError, and Django's get_or_create() can return the committed row through its recovery lookup. If the first transaction rolls back, the second insert can succeed.

PostgreSQL 19's ON CONFLICT DO SELECT inserts or returns the conflicting row in one statement. Under Read Committed isolation, it can return the committed row even when the older same-statement Common Table Expression fallback can't see it.

What does get_or_create() actually execute?

Django's get_or_create() first performs a lookup. On a miss, it attempts creation inside atomic(). After an IntegrityError, it retries the lookup. A database-enforced unique constraint matching the lookup arguments is required for Django's atomicity guarantee. Django's PostgreSQL backend defaults to Read Committed isolation, under which a recovery lookup can see the row after the conflicting transaction commits.

Consider a simple model:

class Tag(models.Model): id \= models.BigAutoField(primary\_key=True) name \= models.CharField(max\_length=100, unique=True) label \= models.CharField(max\_length=100, default="") class Meta: db\_table \= "demo\_tag" 

Django 6.1's get_or_create() follows this simplified flow:

\# Simplified from QuerySet.get\_or\_create(), not replacement code.  self.\_for\_write \= True try: return self.get(\*\*kwargs), False \# SELECT ... WHERE name \= %s  except self.model.DoesNotExist: params \= self.\_extract\_model\_params(defaults, \*\*kwargs) try: with transaction.atomic(using=self.db): \# SAVEPOINT inside outer txn  params \= dict(resolve\_callables(params)) return self.create(\*\*params), True \# INSERT ... RETURNING id  except IntegrityError: try: return self.get(\*\*kwargs), False \# Recovery SELECT  except self.model.DoesNotExist: pass raise 

Django directs the initial lookup to the write database so a stale read replica can't cause a spurious insert attempt. The defaults parameter supplies creation values only. An existing row is returned unchanged with created=False. The inner atomic() block uses a savepoint inside an outer transaction, so an insert error can be rolled back while surrounding work continues. Successful creation doesn't guarantee an outer commit, and in-memory model state isn't automatically restored on rollback.

Django explicitly conditions its atomicity guarantee on database-enforced uniqueness of the lookup arguments. Without a matching constraint, concurrent callers can produce duplicates, and a later lookup can raise MultipleObjectsReturned. For a composite unique constraint, include all constrained columns in the lookup arguments and the conflict target. PostgreSQL also permits multiple nulls in a unique column by default unless NULLS NOT DISTINCT is specified, so a nullable business identifier needs an explicit identity policy.

How PostgreSQL 19's ON CONFLICT DO SELECT works

PostgreSQL 19, released November 19, 2026, adds a DO SELECT conflict action that inserts a new row or returns the existing conflicting row in one statement, with an optional row lock and a RETURNING clause that distinguishes the two paths.

Syntax and return values

DO SELECT requires both a conflict target (an inferred unique index or a named constraint) and a RETURNING clause. Exclusion constraints and deferrable constraints are not supported arbiters.

For Tag, the parameterized statement is:

INSERT INTO demo\_tag (name, label) VALUES (%s, %s) ON CONFLICT (name) DO SELECT RETURNING id, name, label, (OLD.id IS NULL) AS created; 

On insertion, RETURNING yields the new row and OLD is null. On conflict, it yields the existing row unchanged, and NEW equals OLD. The created indicator is a derived expression relying on a non-null primary key and documented OLD/NEW semantics, not a built-in flag.

Locking is optional, not automatic

Without a FOR ... clause, DO SELECT doesn't request an optional lock on the conflicting row. FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, and FOR KEY SHARE are available as explicit choices. The shown statement requires INSERT and SELECT privileges. A locking form also requires UPDATE privilege on at least one column. Fetching a row and committing needs no conflicting-row lock. Fetching a row to modify requires a row lock.

Row locks last until transaction end or savepoint rollback and can cause disk writes.

Choose a lock mode for the concurrent changes that subsequent work must prevent: FOR KEY SHARE permits non-key updates, while FOR UPDATE blocks concurrent updates and deletes until the transaction ends.

Why the CTE workaround can return zero rows

Under Read Committed, each SQL statement sees only rows committed before it began (its MVCC snapshot). A DO NOTHING CTE with a same-statement fallback SELECT can return nothing because MVCC snapshot visibility and uniqueness-conflict detection follow different rules.

Step Session A CTE Session B
1 Inserts key, uncommitted Takes snapshot, cannot see A's row
2 Still holds lock INSERT ... ON CONFLICT DO NOTHING waits
3 Commits Conflict detected; DO NOTHING; CTE returns no row
4 Row committed Fallback SELECT uses original snapshot; row invisible
Result One row exists Zero rows returned

If session A rolls back instead, session B's insert can proceed and return the newly created row.

Under concurrent execution, the CTE can return an empty result. The later SELECT retains the statement-level snapshot.

PostgreSQL 19's DO SELECT closes this gap: the command waits for the conflicting transaction, then returns the committed row under Read Committed. On older versions, an empty-result retry is explicitly recommended. Separate DO NOTHING and SELECT commands can use Read Committed's fresh-command snapshot, but the surrounding algorithm still needs retry logic.

PostgreSQL ON CONFLICT DO SELECT vs CTE DO NOTHING, illustrating how MVCC snapshot visibility can return zero rows while DO SELECT returns the committed row.

Bridging Django and native SQL

Executing native SQL via the cursor path

Django supports direct SQL through connection.cursor(), cursor.execute(), and fetch methods. RawSQL is an expression-fragment API. Manager.raw() maps results to model instances but expects a query returning rows from an existing table. It isn't documented for INSERT ... RETURNING statements.

The Tag examples use Django's default database. If Tag is routed elsewhere, execute through connections[alias].cursor() on its write alias and use transaction.atomic(using=alias) for the locking example. Use Django's %s placeholders with bound parameters. Never interpolate values into the SQL string.

from django.db import connection sql \= """ INSERT INTO demo\_tag (name, label) VALUES (%s, %s) ON CONFLICT (name) DO SELECT RETURNING id, name, label, (OLD.id IS NULL) AS created """ with connection.cursor() as cursor: cursor.execute(sql, \["django", "Django"\]) tag\_id, name, label, created \= cursor.fetchone() 

The returned tuple isn't a Django model instance. Direct cursor execution bypasses model-level construction, Python defaults, save hooks, signal-driven behavior, and relation caches. For row protection during subsequent work, wrap in transaction.atomic() with a locking form such as DO SELECT FOR UPDATE:

from django.db import connection, transaction sql \= """ INSERT INTO demo\_tag (name, label) VALUES (%s, %s) ON CONFLICT (name) DO SELECT FOR UPDATE RETURNING id, name, label, (OLD.id IS NULL) AS created """ with transaction.atomic(): with connection.cursor() as cursor: cursor.execute(sql, \["django", "Django"\]) tag\_id, name, label, created \= cursor.fetchone() \# Dependent work here; row remains locked until atomic() exits.  

The transaction must cover the dependent work, not just the statement that obtains the lock. Even with get_or_create(), concurrent creation through a one-to-one relation can leave stale cache state.

PostgreSQL DO SELECT FOR UPDATE row locking in Django transaction.atomic(), comparing protected dependent work inside a transaction with work after lock release.

When to stay with Django's get_or_create()

Django's get_or_create() returns a hydrated model instance. When it creates a row, it also calls model save() and its signals. For a tag that already exists, get_or_create() returns in one SELECT without touching the insert path. The native statement enters the insert path, detects the conflict, and returns the existing row, which involves conflict-detection work even when no new row is created.

Keep get_or_create() as the default.

Isolation, retries, and what native SQL does not fix

Moving conflict handling into one SQL statement closes the Read Committed visibility gap in the DO NOTHING CTE workaround but doesn't eliminate transaction retries under stronger isolation or guarantee a returned row in every edge case.

Under Repeatable Read or Serializable, serialization failures require retrying the entire transaction, not just the INSERT statement. A DO SELECT ... WHERE condition that evaluates to false for the conflicting row returns zero rows, so the unconditional get-or-create contract no longer holds.

When to keep get_or_create() or use DO SELECT

Feature Django get_or_create() PostgreSQL 19 DO SELECT
Return type Hydrated model instance Row values
created indicator Built-in boolean Derived via (OLD.id IS NULL)
Model lifecycle Creation calls model save() and its signals; an existing-row lookup does not Direct cursor execution bypasses model save() and its signals
Execution path Lookup; insert on a miss; recovery lookup after IntegrityError Single database statement

Keep get_or_create() when the model lifecycle and object contract matter, or when most calls retrieve an existing row. Use a narrow cursor.execute() wrapper when the unique-key identity and returned-value contract fit and most calls insert or contend with concurrent inserters. Test concurrent commits, rollbacks, and transaction retries under the application's configured isolation level before widening use.

Frequently asked questions about get-or-create and ON CONFLICT DO SELECT

Does get_or_create() update an existing row from defaults?

No. defaults supply creation values only. An existing row is returned unchanged. Use update_or_create() for upsert behavior.

Does ON CONFLICT DO SELECT return a created boolean?

Not as a built-in field. Derive it with (OLD.id IS NULL) AS created in the RETURNING clause, relying on a non-null primary key.

Can the CTE workaround be used before PostgreSQL 19?

Yes, but add an empty-result retry. The fallback SELECT in the CTE shares the statement's MVCC snapshot, so it can't see a row committed by a concurrent session after the snapshot was taken.

Will Django adopt DO SELECT behind get_or_create()?

Django's adoption of DO SELECT behind get_or_create() remains unconfirmed.

What happens if I use get_or_create() without a unique constraint?

Without a database-enforced unique constraint on the lookup arguments, concurrent callers can produce duplicate rows. A subsequent lookup may then raise a MultipleObjectsReturned exception.

How does PostgreSQL 19 handle get-or-create race conditions natively?

When a concurrent insert conflicts, PostgreSQL 19's ON CONFLICT DO SELECT waits for that transaction. If it commits, the statement returns the committed row under Read Committed isolation; if it rolls back, the insert can succeed. This closes the visibility gap that breaks older Common Table Expression (CTE) workarounds.