From 25d06247390bab80c4183a39453672d53f20ab4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20N?= Date: Thu, 10 Oct 2024 12:05:10 +0200 Subject: [PATCH] Annotated count fix index error (#1707) * Fix for annotated count * updated changelog * added tests to show what the fix is about --- CHANGELOG.rst | 3 +++ tests/test_aggregation.py | 7 +++++++ tortoise/queryset.py | 2 ++ 3 files changed, 12 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 04c6d693e..e5e4b06c0 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -8,6 +8,9 @@ Changelog 0.21 ==== +0.21.7 +------ +- Fix bug when using annotate and count at the same time but the annotation does not match anything, leading to an IndexError 0.21.6 ------ diff --git a/tests/test_aggregation.py b/tests/test_aggregation.py index 93b2fbcc6..c4c932898 100644 --- a/tests/test_aggregation.py +++ b/tests/test_aggregation.py @@ -236,3 +236,10 @@ async def test_count_after_aggregate_m2m(self): res = await query.count() assert res == 2 + + async def test_count_without_matching(self) -> None: + await Tournament.create(name="Test") + + query = Tournament.annotate(events_count=Count("events")).filter(events_count__gt=0).count() + result = await query + assert result == 0 diff --git a/tortoise/queryset.py b/tortoise/queryset.py index ae3ce5079..6e0e7897f 100644 --- a/tortoise/queryset.py +++ b/tortoise/queryset.py @@ -1335,6 +1335,8 @@ def __await__(self) -> Generator[Any, None, int]: async def _execute(self) -> int: _, result = await self._db.execute_query(str(self.query)) + if not result: + return 0 count = list(dict(result[0]).values())[0] - self.offset if self.limit and count > self.limit: return self.limit