Skip to content

Commit

Permalink
fix refresh if foreign key value has changed (#1059)
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend authored Jul 29, 2024
1 parent 31a76eb commit 9a4a919
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
8 changes: 3 additions & 5 deletions piccolo/query/methods/refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,9 @@ def _get_columns(self, instance: Table, columns: t.Sequence[Column]):
select_columns.extend(
self._get_columns(
child_instance,
column.all_columns(
exclude=[
child_instance.__class__._meta.primary_key
]
),
# Fetch all columns (even the primary key, just in
# case the foreign key now references a different row).
column.all_columns(),
)
)
else:
Expand Down
30 changes: 27 additions & 3 deletions tests/table/test_refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def test_single_layer(self) -> None:

# Refresh `band`, and make sure it has the correct data.
band.refresh().run_sync()
self.assertEqual(self.band.manager.name, "Guido!!!")
self.assertEqual(band.manager.name, "Guido!!!")

def test_multiple_layers(self) -> None:
"""
Expand All @@ -181,15 +181,39 @@ def test_multiple_layers(self) -> None:
Concert.objects(Concert.band_1._.manager)
.where(Concert.band_1._.name == "Pythonistas")
.first()
.run_sync()
)
assert concert is not None

# Modify the data in the database.
self.manager.name = "Guido!!!"
self.manager.save().run_sync()

self.concert.refresh().run_sync()
self.assertEqual(self.concert.band_1.manager.name, "Guido!!!")
concert.refresh().run_sync()
self.assertEqual(concert.band_1.manager.name, "Guido!!!")

def test_updated_foreign_key(self) -> None:
"""
If a foreign key now references a different row, make sure this
is refreshed correctly.
"""
band = (
Band.objects(Band.manager)
.where(Band.name == "Pythonistas")
.first()
.run_sync()
)
assert band is not None

# Assign a different manager to the band
new_manager = Manager({Manager.name: "New Manager"})
new_manager.save().run_sync()
Band.update({Band.manager: new_manager.id}, force=True).run_sync()

# Refresh `band`, and make sure it references the new manager.
band.refresh().run_sync()
self.assertEqual(band.manager.id, new_manager.id)
self.assertEqual(band.manager.name, "New Manager")

def test_exception(self) -> None:
"""
Expand Down

0 comments on commit 9a4a919

Please sign in to comment.