summaryrefslogtreecommitdiff
path: root/django/db/models/sql
diff options
context:
space:
mode:
authorSimon Charette <charette.s@gmail.com>2023-05-21 23:57:49 -0400
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2023-05-23 07:39:24 +0200
commitc78a4421de0fc3240b91d59e8f9028331777c624 (patch)
treef49053887520588c891de36c85fb0951b9c95af0 /django/db/models/sql
parent57f499e412c7c28b4a1f1b740468bf6eabbdb695 (diff)
[4.2.x] Fixed #34551 -- Fixed QuerySet.aggregate() crash when referencing subqueries.
Regression in 59bea9efd2768102fc9d3aedda469502c218e9b7. Refs #28477. Thanks Denis Roldán and Mariusz for the test. Backport of e5c844d6f2a4ac6ae674d741b5f1fa2a688cedf4 from main
Diffstat (limited to 'django/db/models/sql')
-rw-r--r--django/db/models/sql/query.py6
1 files changed, 6 insertions, 0 deletions
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 8739a7b09c..eda37d15f0 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -389,6 +389,7 @@ class Query(BaseExpression):
return {}
# Store annotation mask prior to temporarily adding aggregations for
# resolving purpose to facilitate their subsequent removal.
+ refs_subquery = False
replacements = {}
annotation_select_mask = self.annotation_select_mask
for alias, aggregate_expr in aggregate_exprs.items():
@@ -401,6 +402,10 @@ class Query(BaseExpression):
# Temporarily add aggregate to annotations to allow remaining
# members of `aggregates` to resolve against each others.
self.append_annotation_mask([alias])
+ refs_subquery |= any(
+ getattr(self.annotations[ref], "subquery", False)
+ for ref in aggregate.get_refs()
+ )
aggregate = aggregate.replace_expressions(replacements)
self.annotations[alias] = aggregate
replacements[Ref(alias, aggregate)] = aggregate
@@ -432,6 +437,7 @@ class Query(BaseExpression):
isinstance(self.group_by, tuple)
or self.is_sliced
or has_existing_aggregation
+ or refs_subquery
or qualify
or self.distinct
or self.combinator