summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimon Charette <charette.s@gmail.com>2023-04-06 08:19:53 -0400
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2023-04-07 06:58:24 +0200
commit511dc3db539122577aaba71f5a24d65d5adab092 (patch)
tree9505072d9a18f09a671f8442624fc608cb00b2c6
parent4d6a92749c3e59c6d4fbff385ff04771b9f61961 (diff)
[4.2.x] Fixed #34464 -- Fixed queryset aggregation over group by reference.
Regression in 59bea9efd2768102fc9d3aedda469502c218e9b7. Refs #28477. Thanks Ian Cubitt for the report. Backport of 9daf8b4109c3e133eb57349bb44d73cc60c5773c from main
-rw-r--r--django/db/models/sql/query.py3
-rw-r--r--docs/releases/4.2.1.txt3
-rw-r--r--tests/aggregation/tests.py7
3 files changed, 13 insertions, 0 deletions
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index bb359ae6e8..b347c6bf3f 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -453,6 +453,9 @@ class Query(BaseExpression):
# filtering against window functions is involved as it
# requires complex realising.
annotation_mask = set()
+ if isinstance(self.group_by, tuple):
+ for expr in self.group_by:
+ annotation_mask |= expr.get_refs()
for aggregate in aggregates.values():
annotation_mask |= aggregate.get_refs()
inner_query.set_annotation_mask(annotation_mask)
diff --git a/docs/releases/4.2.1.txt b/docs/releases/4.2.1.txt
index c768b98b18..f8a4edf787 100644
--- a/docs/releases/4.2.1.txt
+++ b/docs/releases/4.2.1.txt
@@ -15,3 +15,6 @@ Bugfixes
* Fixed a regression in Django 4.2 that caused a crash of
:class:`~django.contrib.postgres.search.SearchVector` function with ``%``
characters (:ticket:`34459`).
+
+* Fixed a regression in Django 4.2 that caused aggregation over query that
+ uses explicit grouping to group against the wrong columns (:ticket:`34464`).
diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
index c1ae9f0dd5..ae68c24563 100644
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -36,6 +36,7 @@ from django.db.models.functions import (
Greatest,
Least,
Lower,
+ Mod,
Now,
Pi,
TruncDate,
@@ -2175,3 +2176,9 @@ class AggregateAnnotationPruningTests(TestCase):
sql = ctx.captured_queries[0]["sql"].lower()
self.assertEqual(sql.count("select"), 2, "Subquery wrapping required")
self.assertEqual(sql.count("authors_count"), 2)
+
+ def test_referenced_group_by_annotation_kept(self):
+ queryset = Book.objects.values(pages_mod=Mod("pages", 10)).annotate(
+ mod_count=Count("*")
+ )
+ self.assertEqual(queryset.count(), 1)