Skip to content

Commit

Permalink
1090 fix(m2m): Return empty list if there are no m2m entries (#1089)
Browse files Browse the repository at this point in the history
* fix(m2m): Return empty list if there are no m2m entries

* add a test

---------

Co-authored-by: Daniel Townsend <[email protected]>
  • Loading branch information
nVitius and dantownsend authored Oct 1, 2024
1 parent 36ccc28 commit 5173a39
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
8 changes: 6 additions & 2 deletions piccolo/columns/m2m.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,8 +384,12 @@ async def run(self):
.output(as_list=True)
)

results = await secondary_table.objects().where(
secondary_table._meta.primary_key.is_in(ids)
results = (
await secondary_table.objects().where(
secondary_table._meta.primary_key.is_in(ids)
)
if len(ids) > 0
else []
)

return results
Expand Down
16 changes: 16 additions & 0 deletions tests/columns/m2m/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,22 @@ def test_get_m2m(self):

self.assertEqual([i.name for i in genres], ["Rock", "Folk"])

def test_get_m2m_no_rows(self):
"""
If there are no matching objects, then an empty list should be
returned.
https://github.com/piccolo-orm/piccolo/issues/1090
"""
band = Band.objects().get(Band.name == "Pythonistas").run_sync()
assert band is not None

Genre.delete(force=True).run_sync()

genres = band.get_m2m(Band.genres).run_sync()
self.assertEqual(genres, [])

def test_remove_m2m(self):
"""
Make sure we can remove related items via the joining table.
Expand Down

0 comments on commit 5173a39

Please sign in to comment.