Skip to content

Commit e39c032

Browse files
committed
fix slicing QuerySet.count()
1 parent f11bf9c commit e39c032

File tree

3 files changed

+18
-6
lines changed

3 files changed

+18
-6
lines changed

django_mongodb/compiler.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,17 @@ def get_count(self, check_exists=False):
126126
127127
If `check_exists` is True, only check if any object matches.
128128
"""
129-
kwargs = {"limit": 1} if check_exists else {}
129+
kwargs = {}
130+
# If this query is sliced, the limits will be set on the subquery.
131+
inner_query = getattr(self.query, "inner_query", None)
132+
low_mark = inner_query.low_mark if inner_query else 0
133+
high_mark = inner_query.high_mark if inner_query else None
134+
if low_mark > 0:
135+
kwargs["skip"] = low_mark
136+
if check_exists:
137+
kwargs["limit"] = 1
138+
elif high_mark is not None:
139+
kwargs["limit"] = high_mark - low_mark
130140
try:
131141
return self.build_query().count(**kwargs)
132142
except EmptyResultSet:

django_mongodb/features.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
2626
"lookup.tests.LookupTests.test_exact_none_transform",
2727
# "Save with update_fields did not affect any rows."
2828
"basic.tests.SelectOnSaveTests.test_select_on_save_lying_update",
29-
# Slicing with QuerySet.count() doesn't work.
30-
"lookup.tests.LookupTests.test_count",
3129
# Lookup in order_by() not supported:
3230
# argument of type '<database function>' is not iterable
3331
"db_functions.comparison.test_coalesce.CoalesceTests.test_ordering",

django_mongodb/query.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,16 @@ def fetch(self):
5151
yield from self.get_cursor()
5252

5353
@wrap_database_errors
54-
def count(self, limit=None):
54+
def count(self, limit=None, skip=None):
5555
"""
5656
Return the number of objects that would be returned, if this query was
57-
executed, up to `limit`.
57+
executed, up to `limit`, skipping `skip`.
5858
"""
59-
kwargs = {"limit": limit} if limit is not None else {}
59+
kwargs = {}
60+
if limit is not None:
61+
kwargs["limit"] = limit
62+
if skip is not None:
63+
kwargs["skip"] = skip
6064
return self.collection.count_documents(self.mongo_query, **kwargs)
6165

6266
def order_by(self, ordering):

0 commit comments

Comments
 (0)