From bd337184f1b4901abdfd07b0219d6b9b45d0de2f Mon Sep 17 00:00:00 2001 From: Anssi Kääriäinen Date: Thu, 20 Nov 2014 14:30:25 +0200 Subject: Fixed #23877 -- aggregation's subquery missed target col Aggregation over subquery produced syntactically incorrect queries in some cases as Django didn't ensure that source expressions of the aggregation were present in the subquery. --- django/db/models/sql/compiler.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'django/db/models/sql/compiler.py') diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index dbbc9aecc8..bfce9063e5 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -580,10 +580,10 @@ class SQLCompiler(object): if isinstance(col, (list, tuple)): sql = '%s.%s' % (qn(col[0]), qn(col[1])) elif hasattr(col, 'as_sql'): - self.compile(col) + sql, col_params = self.compile(col) else: sql = '(%s)' % str(col) - if sql not in seen: + if sql not in seen or col_params: result.append(sql) params.extend(col_params) seen.add(sql) @@ -604,6 +604,14 @@ class SQLCompiler(object): sql = '(%s)' % str(extra_select) result.append(sql) params.extend(extra_params) + # Finally, add needed group by cols from annotations + for annotation in self.query.annotation_select.values(): + cols = annotation.get_group_by_cols() + for col in cols: + sql = '%s.%s' % (qn(col[0]), qn(col[1])) + if sql not in seen: + result.append(sql) + seen.add(sql) return result, params -- cgit v1.3