Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

#fixed #2256 -- Made count() interact with slicing on QuerySets. Patc…

…h from

SmileyChris.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@4488 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit d123588184dfecc286e8e06e16dc0383f435c051 1 parent 80e58b3
Malcolm Tredinnick authored
16  django/db/models/query.py
@@ -197,9 +197,12 @@ def count(self):
197 197
         "Performs a SELECT COUNT() and returns the number of records as an integer."
198 198
         counter = self._clone()
199 199
         counter._order_by = ()
  200
+        counter._select_related = False
  201
+        
  202
+        offset = counter._offset
  203
+        limit = counter._limit
200 204
         counter._offset = None
201 205
         counter._limit = None
202  
-        counter._select_related = False
203 206
         
204 207
         try:
205 208
             select, sql, params = counter._get_sql_clause()
@@ -213,7 +216,16 @@ def count(self):
213 216
             cursor.execute("SELECT COUNT(DISTINCT(%s))" % id_col + sql, params)
214 217
         else:
215 218
             cursor.execute("SELECT COUNT(*)" + sql, params)
216  
-        return cursor.fetchone()[0]
  219
+        count = cursor.fetchone()[0]
  220
+
  221
+        # Apply any offset and limit constraints manually, since using LIMIT or
  222
+        # OFFSET in SQL doesn't change the output of COUNT.
  223
+        if offset:
  224
+            count = max(0, count - offset)
  225
+        if limit:
  226
+            count = min(limit, count)
  227
+
  228
+        return count
217 229
 
218 230
     def get(self, *args, **kwargs):
219 231
         "Performs the SELECT and returns a single object matching the given keyword arguments."
11  tests/modeltests/lookup/models.py
@@ -58,6 +58,17 @@ def __str__(self):
58 58
 >>> Article.objects.filter(headline__startswith='Blah blah').count()
59 59
 0L
60 60
 
  61
+# count() should respect sliced query sets.
  62
+>>> articles = Article.objects.all()
  63
+>>> articles.count()
  64
+7L
  65
+>>> articles[:4].count()
  66
+4
  67
+>>> articles[1:100].count()
  68
+6L
  69
+>>> articles[10:100].count()
  70
+0
  71
+
61 72
 # Date and date/time lookups can also be done with strings.
62 73
 >>> Article.objects.filter(pub_date__exact='2005-07-27 00:00:00').count()
63 74
 3L

0 notes on commit d123588

Please sign in to comment.
Something went wrong with that request. Please try again.