Skip to content

Commit a963b75

Browse files
committed
Fix 'pk' not being considered a valid field in deciding which fields update/insert
Fixes #24
1 parent 3efcfb6 commit a963b75

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

psqlextra/compiler.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ def _get_model_field(self, name: str):
219219
# key of a model, we have to respect this de-facto standard behaviour
220220
if field_name == 'pk' and self.query.model._meta.pk:
221221
return self.query.model._meta.pk
222+
222223
for field in self.query.model._meta.local_concrete_fields:
223224
if field.name == field_name or field.column == field_name:
224225
return field

psqlextra/manager.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,14 @@ def _get_upsert_fields(self, kwargs):
328328
update_fields.append(field)
329329
continue
330330

331+
# special handling for 'pk' which always refers to
332+
# the primary key, so if we the user specifies `pk`
333+
# instead of a concrete field, we have to handle that
334+
if field.primary_key is True and 'pk' in kwargs:
335+
insert_fields.append(field)
336+
update_fields.append(field)
337+
continue
338+
331339
if self._is_magical_field(model_instance, field, is_insert=True):
332340
insert_fields.append(field)
333341

tests/test_on_conflict.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,3 +330,6 @@ def test_on_conflict_pk_conflict_target(conflict_action):
330330

331331
assert obj1.name == 'beer'
332332
assert obj2.name == 'beer'
333+
assert obj1.id == obj2.id
334+
assert obj1.id == 0
335+
assert obj2.id == 0

0 commit comments

Comments
 (0)