summaryrefslogtreecommitdiff
path: root/django
diff options
context:
space:
mode:
authorSimon Charette <charette.s@gmail.com>2019-03-08 15:54:03 -0500
committerTim Graham <timograham@gmail.com>2019-03-23 09:50:42 -0400
commitd1e9c25162eecb24dee50fcfe834a2735e53fb0e (patch)
treeb67634047cc88ee8fca3adb610254c8fe09f0aea /django
parentbdc07f176eb7c099ac3fdc42ebaadd48b7f67409 (diff)
Refs #30188 -- Prevented double annotation of subquery when aggregated over.
Thanks Can Sarıgöl for the suggested trimming approach.
Diffstat (limited to 'django')
-rw-r--r--django/db/models/sql/query.py16
1 files changed, 10 insertions, 6 deletions
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 74aed551a3..d421efa7c3 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -383,12 +383,16 @@ class Query(BaseExpression):
new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
new_exprs.append(new_expr)
elif isinstance(expr, (Col, Subquery)) or (expr.contains_aggregate and not expr.is_summary):
- # Reference to column. Make sure the referenced column
- # is selected.
- col_cnt += 1
- col_alias = '__col%d' % col_cnt
- self.annotations[col_alias] = expr
- self.append_annotation_mask([col_alias])
+ # Reference to column, subquery, or another aggregate. Make
+ # sure the expression is selected and reuse its alias if so.
+ for col_alias, selected_annotation in self.annotation_select.items():
+ if selected_annotation == expr:
+ break
+ else:
+ col_cnt += 1
+ col_alias = '__col%d' % col_cnt
+ self.annotations[col_alias] = expr
+ self.append_annotation_mask([col_alias])
new_exprs.append(Ref(col_alias, expr))
else:
# Some other expression not referencing database values