@@ -117,8 +117,13 @@ def cot(self, compiler, connection):
117
117
return {"$divide" : [1 , {"$tan" : lhs_mql }]}
118
118
119
119
120
- def count (self , compiler , connection , force_filters = False , ** extra_context ): # noqa: ARG001
121
- if not self .distinct or force_filters :
120
+ def count (self , compiler , connection , resolve_inner_expression = False , ** extra_context ): # noqa: ARG001
121
+ """
122
+ When resolve_inner_expression is True, it returns the argument as MQL that resolves as a value.
123
+ This is used to count different elements, so the inner values are returned
124
+ to be pushed into a set.
125
+ """
126
+ if not self .distinct or resolve_inner_expression :
122
127
if self .filter :
123
128
copy = self .copy ()
124
129
copy .filter = None
@@ -131,17 +136,21 @@ def count(self, compiler, connection, force_filters=False, **extra_context): #
131
136
condition = When (filter_ , then = Value (1 ))
132
137
copy .set_source_expressions ([Case (condition )] + source_expressions [1 :])
133
138
node = copy
134
- cond = process_lhs (node , compiler , connection )
139
+ inner_expression = process_lhs (node , compiler , connection )
135
140
else :
136
141
node = self
137
142
lhs_mql = process_lhs (self , compiler , connection )
138
143
null_cond = {"$in" : [{"$type" : lhs_mql }, ["missing" , "null" ]]}
139
- cond = {
144
+ inner_expression = {
140
145
"$cond" : {"if" : null_cond , "then" : None , "else" : lhs_mql if self .distinct else 1 }
141
146
}
142
- return {"$sum" : cond }
147
+ if resolve_inner_expression :
148
+ return inner_expression
149
+ return {"$sum" : inner_expression }
143
150
151
+ # When count is called with distinct without the flag, we sum the size of the set.
144
152
lhs_mql = process_lhs (self , compiler , connection )
153
+ # And subtract 1 if None is in the set (it shouldn't have been counted).
145
154
exits_null = {"$cond" : {"if" : {"$in" : [{"$literal" : None }, lhs_mql ]}, "then" : - 1 , "else" : 0 }}
146
155
return {"$add" : [{"$size" : lhs_mql }, exits_null ]}
147
156
0 commit comments