Skip to content

Commit feb4712

Browse files
committed
docstring.
1 parent 98ad0b7 commit feb4712

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

django_mongodb/compiler.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,7 @@ def _prepare_expressions_for_pipeline(self, expression, target, count):
5555
column_target.set_attributes_from_name(alias)
5656
inner_column = Col(self.collection_name, column_target)
5757
if sub_expr.distinct:
58-
inner_expr = sub_expr.as_mql(self, self.connection, force_filters=True)
59-
rhs = next(iter(inner_expr.values()))
58+
rhs = sub_expr.as_mql(self, self.connection, resolve_inner_expression=True)
6059
group[alias] = {"$addToSet": rhs}
6160
replacing_expr = sub_expr.copy()
6261
replacing_expr.set_source_expressions([inner_column])

django_mongodb/functions.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,13 @@ def cot(self, compiler, connection):
117117
return {"$divide": [1, {"$tan": lhs_mql}]}
118118

119119

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:
122127
if self.filter:
123128
copy = self.copy()
124129
copy.filter = None
@@ -131,17 +136,21 @@ def count(self, compiler, connection, force_filters=False, **extra_context): #
131136
condition = When(filter_, then=Value(1))
132137
copy.set_source_expressions([Case(condition)] + source_expressions[1:])
133138
node = copy
134-
cond = process_lhs(node, compiler, connection)
139+
inner_expression = process_lhs(node, compiler, connection)
135140
else:
136141
node = self
137142
lhs_mql = process_lhs(self, compiler, connection)
138143
null_cond = {"$in": [{"$type": lhs_mql}, ["missing", "null"]]}
139-
cond = {
144+
inner_expression = {
140145
"$cond": {"if": null_cond, "then": None, "else": lhs_mql if self.distinct else 1}
141146
}
142-
return {"$sum": cond}
147+
if resolve_inner_expression:
148+
return inner_expression
149+
return {"$sum": inner_expression}
143150

151+
# When count is called with distinct without the flag, we sum the size of the set.
144152
lhs_mql = process_lhs(self, compiler, connection)
153+
# And subtract 1 if None is in the set (it shouldn't have been counted).
145154
exits_null = {"$cond": {"if": {"$in": [{"$literal": None}, lhs_mql]}, "then": -1, "else": 0}}
146155
return {"$add": [{"$size": lhs_mql}, exits_null]}
147156

0 commit comments

Comments
 (0)