Django

Code

Changeset 4488

Show
Ignore:
Timestamp:
02/11/07 18:16:17 (2 years ago)
Author:
mtredinnick
Message:

#fixed #2256 -- Made count() interact with slicing on QuerySets?. Patch from
SmileyChris?.

Files:

Legend:

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

    r4475 r4488  
    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: 
     
    214217        else: 
    215218            cursor.execute("SELECT COUNT(*)" + sql, params) 
    216         return cursor.fetchone()[0] 
     219        count = cursor.fetchone()[0] 
     220 
     221        # Apply any offset and limit constraints manually, since using LIMIT or 
     222        # OFFSET in SQL doesn't change the output of COUNT. 
     223        if offset: 
     224            count = max(0, count - offset) 
     225        if limit: 
     226            count = min(limit, count) 
     227 
     228        return count 
    217229 
    218230    def get(self, *args, **kwargs): 
  • django/trunk/tests/modeltests/lookup/models.py

    r4475 r4488  
    59590L 
    6060 
     61# count() should respect sliced query sets. 
     62>>> articles = Article.objects.all() 
     63>>> articles.count() 
     647L 
     65>>> articles[:4].count() 
     664 
     67>>> articles[1:100].count() 
     686L 
     69>>> articles[10:100].count() 
     700 
     71 
    6172# Date and date/time lookups can also be done with strings. 
    6273>>> Article.objects.filter(pub_date__exact='2005-07-27 00:00:00').count()