Skip to content

Commit d63f659

Browse files
committed
Document condition for upserts
1 parent 6dac0ed commit d63f659

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/source/conflict_handling.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,44 @@ ConflictAction.UPDATE
141141

142142
This is also known as a "upsert".
143143

144+
Condition
145+
"""""""""
146+
147+
Optionally, a condition can be added. PostgreSQL will then only apply the update if the condition holds true. A condition is specified as a custom expression.
148+
149+
A row level lock is acquired before evaluating the condition and proceeding with the update.
150+
151+
.. warning::
152+
153+
The update condition is translated as a condition for `ON CONFLICT`_. The PostgreSQL documentation states the following:
154+
155+
An expression that returns a value of type boolean. Only rows for which this expression returns true will be updated, although all rows will be locked when the ON CONFLICT DO UPDATE action is taken. Note that condition is evaluated last, after a conflict has been identified as a candidate to update.
156+
157+
158+
.. code-block:: python
159+
160+
from django.db.models.expressions import RawSQL
161+
162+
pk = (
163+
MyModel
164+
.objects
165+
.on_conflict(
166+
['name'],
167+
ConflictAction.UPDATE,
168+
update_condition=RawSQL("priority >= EXCLUDED.priority"),
169+
)
170+
.insert(
171+
name='henk',
172+
priority=1,
173+
)
174+
)
175+
176+
if pk:
177+
print('update applied or inserted')
178+
else:
179+
print('condition was false-ish and no changes were made')
180+
181+
144182
145183
ConflictAction.NOTHING
146184
**********************

0 commit comments

Comments
 (0)