Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #1530 -- make count() respect distinct() on QuerySets. Create some

tests for this as well. Thanks to Adam Endicott for the original patch on which
this is based.



git-svn-id: http://code.djangoproject.com/svn/django/trunk@2902 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 1006d6eb06e202a5060d7346973a3dbc3bd0ec53 1 parent aa11b3e
Malcolm Tredinnick authored May 14, 2006
7  django/db/models/query.py
@@ -182,7 +182,12 @@ def count(self):
182 182
         counter._select_related = False
183 183
         select, sql, params = counter._get_sql_clause()
184 184
         cursor = connection.cursor()
185  
-        cursor.execute("SELECT COUNT(*)" + sql, params)
  185
+        if self._distinct:
  186
+            id_col = "%s.%s" % (backend.quote_name(self.model._meta.db_table),
  187
+                    backend.quote_name(self.model._meta.pk.column))
  188
+            cursor.execute("SELECT COUNT(DISTINCT(%s))" % id_col + sql, params)
  189
+        else:
  190
+            cursor.execute("SELECT COUNT(*)" + sql, params)
186 191
         return cursor.fetchone()[0]
187 192
 
188 193
     def get(self, *args, **kwargs):
7  tests/modeltests/many_to_many/models.py
@@ -82,6 +82,13 @@ class Meta:
82 82
 >>> Article.objects.filter(publications__title__startswith="Science").distinct()
83 83
 [NASA uses Python]
84 84
 
  85
+# The count() function respects distinct() as well.
  86
+>>> Article.objects.filter(publications__title__startswith="Science").count()
  87
+2
  88
+
  89
+>>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
  90
+1
  91
+
85 92
 # Reverse m2m queries are supported (i.e., starting at the table that doesn't
86 93
 # have a ManyToManyField).
87 94
 >>> Publication.objects.filter(id__exact=1)
6  tests/modeltests/many_to_one/models.py
@@ -205,6 +205,12 @@ class Meta:
205 205
 >>> Reporter.objects.filter(article__headline__startswith='This').distinct()
206 206
 [John Smith]
207 207
 
  208
+# Counting in the opposite direction works in conjunction with distinct()
  209
+>>> Reporter.objects.filter(article__headline__startswith='This').count()
  210
+3
  211
+>>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()
  212
+1
  213
+
208 214
 # Queries can go round in circles.
209 215
 >>> Reporter.objects.filter(article__reporter__first_name__startswith='John')
210 216
 [John Smith, John Smith, John Smith, John Smith]

0 notes on commit 1006d6e

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