Skip to content

Commit a3fc4e6

Browse files
committed
make sure get_or_create works correctly with joins
1 parent df10b49 commit a3fc4e6

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

piccolo/query/methods/objects.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@ async def run(self):
4848
)
4949
elif isinstance(self.where, And):
5050
for column, value in self.where.get_column_values().items():
51-
setattr(instance, column._meta.name, value)
51+
if len(column._meta.call_chain) == 0:
52+
# Make sure we only set the value if the column belongs
53+
# to this table.
54+
setattr(instance, column._meta.name, value)
5255

5356
for column, value in self.defaults.items():
5457
if isinstance(column, str):

tests/table/test_objects.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,23 @@ def test_get_or_create_very_complex(self):
160160
# The values in the > and < should be ignored, and the default should
161161
# be used for the column.
162162
self.assertEqual(instance.popularity, 0)
163+
164+
def test_get_or_create_with_joins(self):
165+
"""
166+
Make sure that that `get_or_create` creates rows correctly when using
167+
joins.
168+
"""
169+
instance = (
170+
Band.objects()
171+
.get_or_create(
172+
(Band.name == "My new band")
173+
& (Band.manager.name == "Excellent manager")
174+
)
175+
.run_sync()
176+
)
177+
self.assertIsInstance(instance, Band)
178+
self.assertEqual(instance._was_created, True)
179+
180+
# We want to make sure the band name isn't 'Excellent manager' by
181+
# mistake.
182+
self.assertEqual(Band.name, "My new band")

0 commit comments

Comments
 (0)