Menu

1 / 2

PostgreSQL 19 ON CONFLICT DO SELECT vs Django get_or_create()

DEV Community: django·Kamal G·2 days ago
#BjRZqwIl
#devtodjango#devto#dev#select#insert
Long article (2051 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.