Django

Code

Changeset 9007

Show
Ignore:
Timestamp:
09/10/08 21:00:27 (2 months ago)
Author:
mtredinnick
Message:

A bug from queryset-refactor days: although the Query class has "group_by" and
"having" attributes, only the former was included in the resulting SQL, meaning
subclasses had to completely duplicate Query.as_sql() if they were using any
kind of grouping filtering on the results.

Files:

Legend:

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

    r8898 r9007  
    293293            result.append('GROUP BY %s' % ', '.join(grouping)) 
    294294 
     295        if self.having: 
     296            having, h_params = self.get_having() 
     297            result.append('HAVING %s' % ', '.join(having)) 
     298            params.extend(h_params) 
     299 
    295300        if ordering: 
    296301            result.append('ORDER BY %s' % ', '.join(ordering)) 
     
    573578                result.append(str(col)) 
    574579        return result 
     580 
     581    def get_having(self): 
     582        """ 
     583        Returns a tuple representing the SQL elements in the "having" clause. 
     584        By default, the elements of self.having have their as_sql() method 
     585        called or are returned unchanged (if they don't have an as_sql() 
     586        method). 
     587        """ 
     588        result = [] 
     589        params = [] 
     590        for elt in self.having: 
     591            if hasattr(elt, 'as_sql'): 
     592                sql, params = elt.as_sql() 
     593                result.append(sql) 
     594                params.extend(params) 
     595            else: 
     596                result.append(elt) 
     597        return result, params 
    575598 
    576599    def get_ordering(self): 
  • django/trunk/tests/regressiontests/queries/models.py

    r8832 r9007  
    9549541 
    955955 
     956A check to ensure we don't break the internal query construction of GROUP BY 
     957and HAVING. These aren't supported in the public API, but the Query class knows 
     958about them and shouldn't do bad things. 
     959>>> qs = Tag.objects.values_list('parent_id', flat=True).order_by() 
     960>>> qs.query.group_by = ['parent_id'] 
     961>>> qs.query.having = ['count(parent_id) > 1'] 
     962>>> expected = [t3.parent_id, t4.parent_id] 
     963>>> expected.sort() 
     964>>> result = list(qs) 
     965>>> result.sort() 
     966>>> expected == result 
     967True 
     968 
    956969"""} 
    957970