Skip to content

Commit 7727892

Browse files
charettesfelixxm
authored andcommitted
Fixed #35042 -- Fixed a count() crash on combined queries.
Regression in 59bea9e. Thanks Marcin for the report.
1 parent eea4f92 commit 7727892

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

django/db/models/sql/query.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -520,11 +520,11 @@ def get_aggregation(self, using, aggregate_exprs):
520520
self.model._meta.pk.get_col(inner_query.get_initial_alias()),
521521
)
522522
inner_query.default_cols = False
523-
if not qualify:
523+
if not qualify and not self.combinator:
524524
# Mask existing annotations that are not referenced by
525525
# aggregates to be pushed to the outer query unless
526-
# filtering against window functions is involved as it
527-
# requires complex realising.
526+
# filtering against window functions or if the query is
527+
# combined as both would require complex realiasing logic.
528528
annotation_mask = set()
529529
if isinstance(self.group_by, tuple):
530530
for expr in self.group_by:

tests/aggregation/tests.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2344,3 +2344,18 @@ def test_aggregate_reference_lookup_rhs_iter(self):
23442344
max_book_author=Max("book__authors"),
23452345
).aggregate(count=Count("id", filter=Q(id__in=[F("max_book_author"), 0])))
23462346
self.assertEqual(aggregates, {"count": 1})
2347+
2348+
def test_aggregate_combined_queries(self):
2349+
# Combined queries could have members in their values select mask while
2350+
# others have them in their annotation mask which makes annotation
2351+
# pruning complex to implement hence why it's not implemented.
2352+
qs = Author.objects.values(
2353+
"age",
2354+
other=Value(0),
2355+
).union(
2356+
Book.objects.values(
2357+
age=Value(0),
2358+
other=Value(0),
2359+
)
2360+
)
2361+
self.assertEqual(qs.count(), 3)

0 commit comments

Comments
 (0)