From cc4e4d9aee0b3ebfb45bee01aec79edc9e144c78 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 15 Jan 2009 11:06:34 +0000 Subject: Fixed #3566 -- Added support for aggregation to the ORM. See the documentation for details on usage. Many thanks to: * Nicolas Lara, who worked on this feature during the 2008 Google Summer of Code. * Alex Gaynor for his help debugging and fixing a number of issues. * Justin Bronn for his help integrating with contrib.gis. * Karen Tracey for her help with cross-platform testing. * Ian Kelly for his help testing and fixing Oracle support. * Malcolm Tredinnick for his invaluable review notes. git-svn-id: http://code.djangoproject.com/svn/django/trunk@9742 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/sql/subqueries.py | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) (limited to 'django/db/models/sql/subqueries.py') diff --git a/django/db/models/sql/subqueries.py b/django/db/models/sql/subqueries.py index 524b0894c5..0a59b403c8 100644 --- a/django/db/models/sql/subqueries.py +++ b/django/db/models/sql/subqueries.py @@ -9,7 +9,7 @@ from django.db.models.sql.query import Query from django.db.models.sql.where import AND, Constraint __all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'DateQuery', - 'CountQuery'] + 'AggregateQuery'] class DeleteQuery(Query): """ @@ -400,15 +400,25 @@ class DateQuery(Query): self.distinct = True self.order_by = order == 'ASC' and [1] or [-1] -class CountQuery(Query): +class AggregateQuery(Query): """ - A CountQuery knows how to take a normal query which would select over - multiple distinct columns and turn it into SQL that can be used on a - variety of backends (it requires a select in the FROM clause). + An AggregateQuery takes another query as a parameter to the FROM + clause and only selects the elements in the provided list. """ - def get_from_clause(self): - result, params = self._query.as_sql() - return ['(%s) A1' % result], params + def add_subquery(self, query): + self.subquery, self.sub_params = query.as_sql(with_col_aliases=True) - def get_ordering(self): - return () + def as_sql(self, quote_func=None): + """ + Creates the SQL for this query. Returns the SQL string and list of + parameters. + """ + sql = ('SELECT %s FROM (%s) subquery' % ( + ', '.join([ + aggregate.as_sql() + for aggregate in self.aggregate_select.values() + ]), + self.subquery) + ) + params = self.sub_params + return (sql, params) -- cgit v1.3