Commit 1006d6eb authored by Malcolm Tredinnick's avatar Malcolm Tredinnick
Browse files

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
parent aa11b3ea
Loading
Loading
Loading
Loading
+6 −1
Original line number Diff line number Diff line
@@ -182,6 +182,11 @@ class QuerySet(object):
        counter._select_related = False
        select, sql, params = counter._get_sql_clause()
        cursor = connection.cursor()
        if self._distinct:
            id_col = "%s.%s" % (backend.quote_name(self.model._meta.db_table),
                    backend.quote_name(self.model._meta.pk.column))
            cursor.execute("SELECT COUNT(DISTINCT(%s))" % id_col + sql, params)
        else:
            cursor.execute("SELECT COUNT(*)" + sql, params)
        return cursor.fetchone()[0]

+7 −0
Original line number Diff line number Diff line
@@ -82,6 +82,13 @@ API_TESTS = """
>>> Article.objects.filter(publications__title__startswith="Science").distinct()
[NASA uses Python]

# The count() function respects distinct() as well.
>>> Article.objects.filter(publications__title__startswith="Science").count()
2

>>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
1

# Reverse m2m queries are supported (i.e., starting at the table that doesn't
# have a ManyToManyField).
>>> Publication.objects.filter(id__exact=1)
+6 −0
Original line number Diff line number Diff line
@@ -205,6 +205,12 @@ John Smith
>>> Reporter.objects.filter(article__headline__startswith='This').distinct()
[John Smith]

# Counting in the opposite direction works in conjunction with distinct()
>>> Reporter.objects.filter(article__headline__startswith='This').count()
3
>>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()
1

# Queries can go round in circles.
>>> Reporter.objects.filter(article__reporter__first_name__startswith='John')
[John Smith, John Smith, John Smith, John Smith]