Fixed #34750 -- Fixed QuerySet.count() when grouping by unused multi-valued annotations.

Thanks Toan Vuong for the report.
Thanks Simon Charette for the review.

Regression in 59bea9efd2.
This commit is contained in:
Mariusz Felisiak 2023-08-01 16:16:28 +02:00 committed by GitHub
parent 5a3725594f
commit c9b9a52edc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 50 additions and 0 deletions

View file

@ -2165,6 +2165,47 @@ class AggregateAnnotationPruningTests(TestCase):
self.assertEqual(sql.count("select"), 2, "Subquery wrapping required")
self.assertNotIn("authors_count", sql)
def test_unused_aliased_aggregate_and_annotation_reverse_fk(self):
Book.objects.create(
name="b3",
publisher=self.p2,
pages=1000,
rating=4.2,
price=50,
contact=self.a2,
pubdate=datetime.date.today(),
)
qs = Publisher.objects.annotate(
total_pages=Sum("book__pages"),
good_book=Case(
When(book__rating__gt=4.0, then=Value(True)),
default=Value(False),
),
)
self.assertEqual(qs.count(), 3)
def test_unused_aliased_aggregate_and_annotation_reverse_fk_grouped(self):
Book.objects.create(
name="b3",
publisher=self.p2,
pages=1000,
rating=4.2,
price=50,
contact=self.a2,
pubdate=datetime.date.today(),
)
qs = (
Publisher.objects.values("id", "name")
.annotate(total_pages=Sum("book__pages"))
.annotate(
good_book=Case(
When(book__rating__gt=4.0, then=Value(True)),
default=Value(False),
)
)
)
self.assertEqual(qs.count(), 3)
def test_non_aggregate_annotation_pruned(self):
with CaptureQueriesContext(connection) as ctx:
Book.objects.annotate(