Bug fix: QuerySet.count() ignores slicing

This commit is contained in:
Itai Shirav 2018-10-13 19:29:36 +03:00
parent 928e41b82c
commit f2a731711d
3 changed files with 12 additions and 1 deletions

View File

@ -1,6 +1,10 @@
Change Log Change Log
========== ==========
Unreleased
----------
- Bug fix: `QuerySet.count()` ignores slicing
v1.0.2 v1.0.2
---------- ----------
- Include alias and materialized fields in queryset results - Include alias and materialized fields in queryset results

View File

@ -316,11 +316,12 @@ class QuerySet(object):
""" """
Returns the number of matching model instances. Returns the number of matching model instances.
""" """
if self._distinct: if self._distinct or self._limits:
# Use a subquery, since a simple count won't be accurate # Use a subquery, since a simple count won't be accurate
sql = u'SELECT count() FROM (%s)' % self.as_sql() sql = u'SELECT count() FROM (%s)' % self.as_sql()
raw = self._database.raw(sql) raw = self._database.raw(sql)
return int(raw) if raw else 0 return int(raw) if raw else 0
# Simple case
return self._database.count(self._model_cls, self.conditions_as_sql()) return self._database.count(self._model_cls, self.conditions_as_sql())
def order_by(self, *field_names): def order_by(self, *field_names):

View File

@ -239,6 +239,12 @@ class QuerySetTestCase(TestCaseWithData):
for obj in qs: for obj in qs:
self.assertTrue(obj.num_squared == obj.num ** 2) self.assertTrue(obj.num_squared == obj.num ** 2)
def test_count_of_slice(self):
qs = Person.objects_in(self.database)
self._test_qs(qs[:70], 70)
self._test_qs(qs[70:80], 10)
self._test_qs(qs[80:], 20)
class AggregateTestCase(TestCaseWithData): class AggregateTestCase(TestCaseWithData):