Ticket #2939: django-distinct-values-count.diff

File django-distinct-values-count.diff, 1.6 KB (added by andrew@…, 18 years ago)

patch to add count method to ValuesQuerySet, better handling distinct case

  • django/db/models/query.py

     
    533533            for row in rows:
    534534                yield dict(zip(field_names, row))
    535535
     536    def count(self):
     537        "Performs a SELECT COUNT() and returns the number of records as an integer."
     538        counter = self._clone()
     539        counter._order_by = ()
     540        counter._offset = None
     541        counter._limit = None
     542        counter._select_related = False
     543        select, sql, params = counter._get_sql_clause()
     544        cursor = connection.cursor()
     545
     546        # self._fields is a list of field names to fetch.
     547        if self._fields:
     548            columns = [self.model._meta.get_field(f, many_to_many=False).column for f in self._fields]
     549            column_names = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns]
     550            select_spec = ', '.join(column_names)
     551        else: # Default to id_col
     552            select_spec = "%s.%s" % (backend.quote_name(self.model._meta.db_table),
     553                    backend.quote_name(self.model._meta.pk.column))
     554
     555        if self._distinct:
     556            cursor.execute("SELECT COUNT(DISTINCT(%s))" % select_spec + sql, params)
     557        else:
     558            cursor.execute("SELECT COUNT(*)" + sql, params)
     559        return cursor.fetchone()[0]
     560
    536561    def _clone(self, klass=None, **kwargs):
    537562        c = super(ValuesQuerySet, self)._clone(klass, **kwargs)
    538563        c._fields = self._fields[:]
Back to Top