Skip to content

Commit

Permalink
Fixed #35042 -- Fixed a count() crash on combined queries.
Browse files Browse the repository at this point in the history
Regression in 59bea9e.

Thanks Marcin for the report.
  • Loading branch information
charettes authored and felixxm committed Dec 16, 2023
1 parent eea4f92 commit 7727892
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 3 additions & 3 deletions django/db/models/sql/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,11 +520,11 @@ def get_aggregation(self, using, aggregate_exprs):
self.model._meta.pk.get_col(inner_query.get_initial_alias()),
)
inner_query.default_cols = False
if not qualify:
if not qualify and not self.combinator:
# Mask existing annotations that are not referenced by
# aggregates to be pushed to the outer query unless
# filtering against window functions is involved as it
# requires complex realising.
# filtering against window functions or if the query is
# combined as both would require complex realiasing logic.
annotation_mask = set()
if isinstance(self.group_by, tuple):
for expr in self.group_by:
Expand Down
15 changes: 15 additions & 0 deletions tests/aggregation/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2344,3 +2344,18 @@ def test_aggregate_reference_lookup_rhs_iter(self):
max_book_author=Max("book__authors"),
).aggregate(count=Count("id", filter=Q(id__in=[F("max_book_author"), 0])))
self.assertEqual(aggregates, {"count": 1})

def test_aggregate_combined_queries(self):
# Combined queries could have members in their values select mask while
# others have them in their annotation mask which makes annotation
# pruning complex to implement hence why it's not implemented.
qs = Author.objects.values(
"age",
other=Value(0),
).union(
Book.objects.values(
age=Value(0),
other=Value(0),
)
)
self.assertEqual(qs.count(), 3)

0 comments on commit 7727892

Please sign in to comment.