Ticket #2256: queryset_count.patch

File queryset_count.patch, 1.5 KB (added by Chris Beaven, 17 years ago)
  • django/db/models/query.py

     
    197197        "Performs a SELECT COUNT() and returns the number of records as an integer."
    198198        counter = self._clone()
    199199        counter._order_by = ()
     200        counter._select_related = False
     201       
     202        offset = counter._offset
     203        limit = counter._limit
    200204        counter._offset = None
    201205        counter._limit = None
    202         counter._select_related = False
    203206       
    204207        try:
    205208            select, sql, params = counter._get_sql_clause()
    206         except EmptyResultSet:
     209        except EmptyResultSet: 
    207210            return 0
    208211           
    209212        cursor = connection.cursor()
     
    213216            cursor.execute("SELECT COUNT(DISTINCT(%s))" % id_col + sql, params)
    214217        else:
    215218            cursor.execute("SELECT COUNT(*)" + sql, params)
    216         return cursor.fetchone()[0]
     219        count = cursor.fetchone()[0]
    217220
     221        # Apply any offset and limit since using LIMIT or OFFSET in SQL doesn't
     222        # change the output of COUNT.
     223        if offset:
     224            count -= offset
     225        if limit:
     226            count = min(limit, count)
     227
     228        return count
     229
    218230    def get(self, *args, **kwargs):
    219231        "Performs the SELECT and returns a single object matching the given keyword arguments."
    220232        clone = self.filter(*args, **kwargs)
Back to Top