Django

Code

Changeset 2902

Show
Ignore:
Timestamp:
05/14/06 18:49:29 (2 years ago)
Author:
mtredinnick
Message:

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.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/query.py

    r2859 r2902  
    183183        select, sql, params = counter._get_sql_clause() 
    184184        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) 
    186191        return cursor.fetchone()[0] 
    187192 
  • django/trunk/tests/modeltests/many_to_many/models.py

    r2817 r2902  
    8383[NASA uses Python] 
    8484 
     85# The count() function respects distinct() as well. 
     86>>> Article.objects.filter(publications__title__startswith="Science").count() 
     872 
     88 
     89>>> Article.objects.filter(publications__title__startswith="Science").distinct().count() 
     901 
     91 
    8592# Reverse m2m queries are supported (i.e., starting at the table that doesn't 
    8693# have a ManyToManyField). 
  • django/trunk/tests/modeltests/many_to_one/models.py

    r2809 r2902  
    205205>>> Reporter.objects.filter(article__headline__startswith='This').distinct() 
    206206[John Smith] 
     207 
     208# Counting in the opposite direction works in conjunction with distinct() 
     209>>> Reporter.objects.filter(article__headline__startswith='This').count() 
     2103 
     211>>> Reporter.objects.filter(article__headline__startswith='This').distinct().count() 
     2121 
    207213 
    208214# Queries can go round in circles.