| 32 | The bug is reproducible with an extra test on the django aggregation test suite: |
| 33 | |
| 34 | |
| 35 | {{{ |
| 36 | def test_referenced_group_by_aggregation_over_annotation(self): |
| 37 | total_books_qs = ( |
| 38 | Book.objects.filter(authors__pk=OuterRef("pk")) |
| 39 | .order_by() |
| 40 | .values("pk") |
| 41 | .annotate(total=Count("pk")) |
| 42 | .values("total") |
| 43 | ) |
| 44 | |
| 45 | annotated_authors = Author.objects.annotate( |
| 46 | total_books=Subquery(total_books_qs.annotate( |
| 47 | total_books=F("total") |
| 48 | ).values("total_books")), |
| 49 | total_books_a=Subquery(total_books_qs.filter( |
| 50 | name__istartswith="a" |
| 51 | ).annotate( |
| 52 | total_books_a=F("total") |
| 53 | ).values("total_books_a")), |
| 54 | ).values( |
| 55 | "pk", |
| 56 | "total_books", |
| 57 | "total_books_a", |
| 58 | ).order_by("-total_books") |
| 59 | |
| 60 | totals = annotated_authors.aggregate( |
| 61 | sum_total_books=Sum("total_books"), |
| 62 | sum_total_books_a=Sum("total_books_a"), |
| 63 | a_over_total_rate=Case( |
| 64 | When( |
| 65 | sum_total_books=0, |
| 66 | then=0, |
| 67 | ), |
| 68 | default=Round( |
| 69 | (Sum("total_books_a") / Sum("total_books")) * 100, 2 |
| 70 | ), |
| 71 | output_field=FloatField(), |
| 72 | ), |
| 73 | ) |
| 74 | |
| 75 | self.assertEqual(totals['sum_total_books'], 3) |
| 76 | self.assertEqual(totals['sum_total_books_a'], 0) |
| 77 | self.assertEqual(totals['a_over_total_rate'], 0) |
| 78 | |
| 79 | }}} |
| 80 | |
| 81 | |