Fix collerek/ormar#588 Bug in queryset count() method

This commit is contained in:
haydeec1
2022-03-09 17:06:54 -05:00
parent 989e11e066
commit a7e78bbf8c
2 changed files with 16 additions and 1 deletions

View File

@ -678,7 +678,7 @@ class QuerySet(Generic[T]):
expr = sqlalchemy.exists(expr).select() expr = sqlalchemy.exists(expr).select()
return await self.database.fetch_val(expr) return await self.database.fetch_val(expr)
async def count(self) -> int: async def count(self, distinct: bool = True) -> int:
""" """
Returns number of rows matching the given criteria Returns number of rows matching the given criteria
(applied with `filter` and `exclude` if set before). (applied with `filter` and `exclude` if set before).
@ -688,6 +688,9 @@ class QuerySet(Generic[T]):
""" """
expr = self.build_select_expression().alias("subquery_for_count") expr = self.build_select_expression().alias("subquery_for_count")
expr = sqlalchemy.func.count().select().select_from(expr) expr = sqlalchemy.func.count().select().select_from(expr)
if distinct:
expr_distinct = expr.group_by(self.model_meta.pkname).alias("subquery_for_group")
expr = sqlalchemy.func.count().select().select_from(expr_distinct)
return await self.database.fetch_val(expr) return await self.database.fetch_val(expr)
async def _query_aggr_function(self, func_name: str, columns: List) -> Any: async def _query_aggr_function(self, func_name: str, columns: List) -> Any:

View File

@ -175,3 +175,15 @@ async def test_queryset_method():
assert await author.books.max(["year", "title"]) == dict( assert await author.books.max(["year", "title"]) == dict(
year=1930, title="Book 3" year=1930, title="Book 3"
) )
@pytest.mark.asyncio
async def test_count_method():
async with database:
await sample_data()
count = await Author.objects.select_related("books").count()
assert count == 1
# The legacy functionality
count = await Author.objects.select_related("books").count(distinct=False)
assert count == 3