diff options
Diffstat (limited to 'django')
| -rw-r--r-- | django/db/models/expressions.py | 1 | ||||
| -rw-r--r-- | django/db/models/sql/query.py | 6 |
2 files changed, 7 insertions, 0 deletions
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index e1861759c4..280cb967b4 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -1541,6 +1541,7 @@ class Subquery(BaseExpression, Combinable): template = "(%(subquery)s)" contains_aggregate = False empty_result_set_value = None + subquery = True def __init__(self, queryset, output_field=None, **extra): # Allow the usage of both QuerySet and sql.Query objects. diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index c4b435df2d..781dfd5499 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -402,6 +402,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(): @@ -414,6 +415,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 @@ -445,6 +450,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 |
