summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMariusz Felisiak <felisiak.mariusz@gmail.com>2018-05-28 00:25:19 +0200
committerTim Graham <timograham@gmail.com>2018-05-27 18:25:42 -0400
commitb6e48f514ebe4e31b76e1750e043d4f296e645dc (patch)
tree2270b406b7232240ca38779bf9ec1af3969092c2
parent158e7804e780aa4dd227847856d14cf3214c2d67 (diff)
[2.1.x] Fixed #29416 -- Removed unnecesary subquery from GROUP BY clause on MySQL when using a RawSQL annotation.
Regression in 1d070d027c218285b66c0bde8079034b33a87f11. Backport of 4ab1f559e8d1264bcb20bb497988973194f5d8f2 from master
-rw-r--r--django/db/models/sql/compiler.py4
-rw-r--r--docs/releases/2.0.6.txt3
-rw-r--r--tests/annotations/tests.py12
3 files changed, 18 insertions, 1 deletions
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index f5222f21be..8b0fd1da46 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -157,7 +157,9 @@ class SQLCompiler:
}
expressions = [pk] + [
expr for expr in expressions
- if expr in having or getattr(expr, 'alias', None) not in pk_aliases
+ if expr in having or (
+ getattr(expr, 'alias', None) is not None and expr.alias not in pk_aliases
+ )
]
elif self.connection.features.allows_group_by_selected_pks:
# Filter out all expressions associated with a table's primary key
diff --git a/docs/releases/2.0.6.txt b/docs/releases/2.0.6.txt
index 1c9d0982fa..9652e4e63d 100644
--- a/docs/releases/2.0.6.txt
+++ b/docs/releases/2.0.6.txt
@@ -14,3 +14,6 @@ Bugfixes
* Fixed detection of custom URL converters in included patterns
(:ticket:`29415`).
+
+* Fixed a regression that added an unnecessary subquery to the ``GROUP BY``
+ clause on MySQL when using a ``RawSQL`` annotation (:ticket:`29416`).
diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py
index f7f8474329..4fc7e6f047 100644
--- a/tests/annotations/tests.py
+++ b/tests/annotations/tests.py
@@ -6,6 +6,7 @@ from django.db.models import (
BooleanField, CharField, Count, DateTimeField, ExpressionWrapper, F, Func,
IntegerField, NullBooleanField, Q, Sum, Value,
)
+from django.db.models.expressions import RawSQL
from django.db.models.functions import Length, Lower
from django.test import TestCase, skipUnlessDBFeature
@@ -322,6 +323,17 @@ class NonAggregateAnnotationTestCase(TestCase):
for publisher in publishers.filter(pk=self.p1.pk):
self.assertEqual(publisher['book__rating'], publisher['total'])
+ @skipUnlessDBFeature('allows_group_by_pk')
+ def test_rawsql_group_by_collapse(self):
+ raw = RawSQL('SELECT MIN(id) FROM annotations_book', [])
+ qs = Author.objects.values('id').annotate(
+ min_book_id=raw,
+ count_friends=Count('friends'),
+ ).order_by()
+ _, _, group_by = qs.query.get_compiler(using='default').pre_sql_setup()
+ self.assertEqual(len(group_by), 1)
+ self.assertNotEqual(raw, group_by[0])
+
def test_defer_annotation(self):
"""
Deferred attributes can be referenced by an annotation,