Skip to content

Commit a7e78bb

Browse files
haydeec1haydeec1
authored andcommitted
Fix #588 Bug in queryset count() method
1 parent 989e11e commit a7e78bb

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

ormar/queryset/queryset.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,7 @@ async def exists(self) -> bool:
678678
expr = sqlalchemy.exists(expr).select()
679679
return await self.database.fetch_val(expr)
680680

681-
async def count(self) -> int:
681+
async def count(self, distinct: bool = True) -> int:
682682
"""
683683
Returns number of rows matching the given criteria
684684
(applied with `filter` and `exclude` if set before).
@@ -688,6 +688,9 @@ async def count(self) -> int:
688688
"""
689689
expr = self.build_select_expression().alias("subquery_for_count")
690690
expr = sqlalchemy.func.count().select().select_from(expr)
691+
if distinct:
692+
expr_distinct = expr.group_by(self.model_meta.pkname).alias("subquery_for_group")
693+
expr = sqlalchemy.func.count().select().select_from(expr_distinct)
691694
return await self.database.fetch_val(expr)
692695

693696
async def _query_aggr_function(self, func_name: str, columns: List) -> Any:

tests/test_queries/test_aggr_functions.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,3 +175,15 @@ async def test_queryset_method():
175175
assert await author.books.max(["year", "title"]) == dict(
176176
year=1930, title="Book 3"
177177
)
178+
179+
@pytest.mark.asyncio
180+
async def test_count_method():
181+
async with database:
182+
await sample_data()
183+
184+
count = await Author.objects.select_related("books").count()
185+
assert count == 1
186+
187+
# The legacy functionality
188+
count = await Author.objects.select_related("books").count(distinct=False)
189+
assert count == 3

0 commit comments

Comments
 (0)