From d5ce2dd7bc5b797d2e338c4bc6e6f3e339b748e5 Mon Sep 17 00:00:00 2001 From: Anssi Kääriäinen Date: Tue, 5 May 2015 14:44:33 +0300 Subject: [1.8.x] Fixed #24748 -- Fixed incorrect GROUP BY on MySQL in some queries When the query's model had a self-referential foreign key, the compiler.get_group_by() code incorrectly used the self-referential foreign key's column (for example parent_id) as GROUP BY clause when it should have used the model's primary key column (id). Backport of adc57632bc26cc8fe42bdb6aff463f883214980a from master --- django/db/models/sql/compiler.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'django/db/models/sql') diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 810031f47e..6aab204598 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -145,9 +145,12 @@ class SQLCompiler(object): # then also add having expressions to group by. pk = None for expr in expressions: - if (expr.output_field.primary_key and - getattr(expr.output_field, 'model') == self.query.model): + # Is this a reference to query's base table primary key? If the + # expression isn't a Col-like, then skip the expression. + if (getattr(expr, 'target', None) == self.query.model._meta.pk and + getattr(expr, 'alias', None) == self.query.tables[0]): pk = expr + break if pk: expressions = [pk] + [expr for expr in expressions if expr in having] return expressions -- cgit v1.3