Skip to content

Commit 7436393

Browse files
committed
Document the right way to write expression for upsert conditions
1 parent d63f659 commit 7436393

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

docs/source/conflict_handling.rst

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,13 +148,31 @@ Optionally, a condition can be added. PostgreSQL will then only apply the update
148148

149149
A row level lock is acquired before evaluating the condition and proceeding with the update.
150150

151-
.. warning::
151+
.. note::
152152

153153
The update condition is translated as a condition for `ON CONFLICT`_. The PostgreSQL documentation states the following:
154154

155155
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.
156156

157157

158+
.. warning::
159+
160+
Always parameterize the input to avoid SQL injections.
161+
162+
Do:
163+
164+
.. code-block:: python
165+
166+
my_name = 'henk'
167+
RawSQL("name != %s", (my_name,))
168+
169+
Not:
170+
171+
.. code-block:: python
172+
173+
RawSQL("name != + henk, tuple())
174+
175+
158176
.. code-block:: python
159177
160178
from django.db.models.expressions import RawSQL
@@ -179,6 +197,13 @@ A row level lock is acquired before evaluating the condition and proceeding with
179197
print('condition was false-ish and no changes were made')
180198
181199
200+
When writing expressions, refer to the data you're trying to upsert with ``EXCLUDED``. Refer to the existing row by prefixing the name of the table:
201+
202+
.. code-block:: python
203+
204+
RawSQL(MyModel._meta.db_table + '.mycolumn = EXCLUDED.mycolumn')
205+
206+
182207
183208
ConflictAction.NOTHING
184209
**********************

0 commit comments

Comments
 (0)