File tree Expand file tree Collapse file tree 2 files changed +16
-1
lines changed Expand file tree Collapse file tree 2 files changed +16
-1
lines changed Original file line number Diff line number Diff line change @@ -678,7 +678,7 @@ async def exists(self) -> bool:
678
678
expr = sqlalchemy .exists (expr ).select ()
679
679
return await self .database .fetch_val (expr )
680
680
681
- async def count (self ) -> int :
681
+ async def count (self , distinct : bool = True ) -> int :
682
682
"""
683
683
Returns number of rows matching the given criteria
684
684
(applied with `filter` and `exclude` if set before).
@@ -688,6 +688,9 @@ async def count(self) -> int:
688
688
"""
689
689
expr = self .build_select_expression ().alias ("subquery_for_count" )
690
690
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 )
691
694
return await self .database .fetch_val (expr )
692
695
693
696
async def _query_aggr_function (self , func_name : str , columns : List ) -> Any :
Original file line number Diff line number Diff line change @@ -175,3 +175,15 @@ async def test_queryset_method():
175
175
assert await author .books .max (["year" , "title" ]) == dict (
176
176
year = 1930 , title = "Book 3"
177
177
)
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
You can’t perform that action at this time.
0 commit comments