1. import datetime
    
  2. import pickle
    
  3. from decimal import Decimal
    
  4. from operator import attrgetter
    
  5. from unittest import mock
    
  6. 
    
  7. from django.contrib.contenttypes.models import ContentType
    
  8. from django.core.exceptions import FieldError
    
  9. from django.db import connection
    
  10. from django.db.models import (
    
  11.     Aggregate,
    
  12.     Avg,
    
  13.     Case,
    
  14.     Count,
    
  15.     DecimalField,
    
  16.     F,
    
  17.     IntegerField,
    
  18.     Max,
    
  19.     Q,
    
  20.     StdDev,
    
  21.     Sum,
    
  22.     Value,
    
  23.     Variance,
    
  24.     When,
    
  25. )
    
  26. from django.test import TestCase, skipUnlessAnyDBFeature, skipUnlessDBFeature
    
  27. from django.test.utils import Approximate
    
  28. 
    
  29. from .models import (
    
  30.     Alfa,
    
  31.     Author,
    
  32.     Book,
    
  33.     Bravo,
    
  34.     Charlie,
    
  35.     Clues,
    
  36.     Entries,
    
  37.     HardbackBook,
    
  38.     ItemTag,
    
  39.     Publisher,
    
  40.     SelfRefFK,
    
  41.     Store,
    
  42.     WithManualPK,
    
  43. )
    
  44. 
    
  45. 
    
  46. class AggregationTests(TestCase):
    
  47.     @classmethod
    
  48.     def setUpTestData(cls):
    
  49.         cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34)
    
  50.         cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35)
    
  51.         cls.a3 = Author.objects.create(name="Brad Dayley", age=45)
    
  52.         cls.a4 = Author.objects.create(name="James Bennett", age=29)
    
  53.         cls.a5 = Author.objects.create(name="Jeffrey Forcier", age=37)
    
  54.         cls.a6 = Author.objects.create(name="Paul Bissex", age=29)
    
  55.         cls.a7 = Author.objects.create(name="Wesley J. Chun", age=25)
    
  56.         cls.a8 = Author.objects.create(name="Peter Norvig", age=57)
    
  57.         cls.a9 = Author.objects.create(name="Stuart Russell", age=46)
    
  58.         cls.a1.friends.add(cls.a2, cls.a4)
    
  59.         cls.a2.friends.add(cls.a1, cls.a7)
    
  60.         cls.a4.friends.add(cls.a1)
    
  61.         cls.a5.friends.add(cls.a6, cls.a7)
    
  62.         cls.a6.friends.add(cls.a5, cls.a7)
    
  63.         cls.a7.friends.add(cls.a2, cls.a5, cls.a6)
    
  64.         cls.a8.friends.add(cls.a9)
    
  65.         cls.a9.friends.add(cls.a8)
    
  66. 
    
  67.         cls.p1 = Publisher.objects.create(name="Apress", num_awards=3)
    
  68.         cls.p2 = Publisher.objects.create(name="Sams", num_awards=1)
    
  69.         cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7)
    
  70.         cls.p4 = Publisher.objects.create(name="Morgan Kaufmann", num_awards=9)
    
  71.         cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0)
    
  72. 
    
  73.         cls.b1 = Book.objects.create(
    
  74.             isbn="159059725",
    
  75.             name="The Definitive Guide to Django: Web Development Done Right",
    
  76.             pages=447,
    
  77.             rating=4.5,
    
  78.             price=Decimal("30.00"),
    
  79.             contact=cls.a1,
    
  80.             publisher=cls.p1,
    
  81.             pubdate=datetime.date(2007, 12, 6),
    
  82.         )
    
  83.         cls.b2 = Book.objects.create(
    
  84.             isbn="067232959",
    
  85.             name="Sams Teach Yourself Django in 24 Hours",
    
  86.             pages=528,
    
  87.             rating=3.0,
    
  88.             price=Decimal("23.09"),
    
  89.             contact=cls.a3,
    
  90.             publisher=cls.p2,
    
  91.             pubdate=datetime.date(2008, 3, 3),
    
  92.         )
    
  93.         cls.b3 = Book.objects.create(
    
  94.             isbn="159059996",
    
  95.             name="Practical Django Projects",
    
  96.             pages=300,
    
  97.             rating=4.0,
    
  98.             price=Decimal("29.69"),
    
  99.             contact=cls.a4,
    
  100.             publisher=cls.p1,
    
  101.             pubdate=datetime.date(2008, 6, 23),
    
  102.         )
    
  103.         cls.b4 = Book.objects.create(
    
  104.             isbn="013235613",
    
  105.             name="Python Web Development with Django",
    
  106.             pages=350,
    
  107.             rating=4.0,
    
  108.             price=Decimal("29.69"),
    
  109.             contact=cls.a5,
    
  110.             publisher=cls.p3,
    
  111.             pubdate=datetime.date(2008, 11, 3),
    
  112.         )
    
  113.         cls.b5 = HardbackBook.objects.create(
    
  114.             isbn="013790395",
    
  115.             name="Artificial Intelligence: A Modern Approach",
    
  116.             pages=1132,
    
  117.             rating=4.0,
    
  118.             price=Decimal("82.80"),
    
  119.             contact=cls.a8,
    
  120.             publisher=cls.p3,
    
  121.             pubdate=datetime.date(1995, 1, 15),
    
  122.             weight=4.5,
    
  123.         )
    
  124.         cls.b6 = HardbackBook.objects.create(
    
  125.             isbn="155860191",
    
  126.             name=(
    
  127.                 "Paradigms of Artificial Intelligence Programming: Case Studies in "
    
  128.                 "Common Lisp"
    
  129.             ),
    
  130.             pages=946,
    
  131.             rating=5.0,
    
  132.             price=Decimal("75.00"),
    
  133.             contact=cls.a8,
    
  134.             publisher=cls.p4,
    
  135.             pubdate=datetime.date(1991, 10, 15),
    
  136.             weight=3.7,
    
  137.         )
    
  138.         cls.b1.authors.add(cls.a1, cls.a2)
    
  139.         cls.b2.authors.add(cls.a3)
    
  140.         cls.b3.authors.add(cls.a4)
    
  141.         cls.b4.authors.add(cls.a5, cls.a6, cls.a7)
    
  142.         cls.b5.authors.add(cls.a8, cls.a9)
    
  143.         cls.b6.authors.add(cls.a8)
    
  144. 
    
  145.         s1 = Store.objects.create(
    
  146.             name="Amazon.com",
    
  147.             original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42),
    
  148.             friday_night_closing=datetime.time(23, 59, 59),
    
  149.         )
    
  150.         s2 = Store.objects.create(
    
  151.             name="Books.com",
    
  152.             original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37),
    
  153.             friday_night_closing=datetime.time(23, 59, 59),
    
  154.         )
    
  155.         s3 = Store.objects.create(
    
  156.             name="Mamma and Pappa's Books",
    
  157.             original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14),
    
  158.             friday_night_closing=datetime.time(21, 30),
    
  159.         )
    
  160.         s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6)
    
  161.         s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6)
    
  162.         s3.books.add(cls.b3, cls.b4, cls.b6)
    
  163. 
    
  164.     def assertObjectAttrs(self, obj, **kwargs):
    
  165.         for attr, value in kwargs.items():
    
  166.             self.assertEqual(getattr(obj, attr), value)
    
  167. 
    
  168.     def test_annotation_with_value(self):
    
  169.         values = (
    
  170.             Book.objects.filter(
    
  171.                 name="Practical Django Projects",
    
  172.             )
    
  173.             .annotate(
    
  174.                 discount_price=F("price") * 2,
    
  175.             )
    
  176.             .values(
    
  177.                 "discount_price",
    
  178.             )
    
  179.             .annotate(sum_discount=Sum("discount_price"))
    
  180.         )
    
  181.         self.assertSequenceEqual(
    
  182.             values,
    
  183.             [{"discount_price": Decimal("59.38"), "sum_discount": Decimal("59.38")}],
    
  184.         )
    
  185. 
    
  186.     def test_aggregates_in_where_clause(self):
    
  187.         """
    
  188.         Regression test for #12822: DatabaseError: aggregates not allowed in
    
  189.         WHERE clause
    
  190. 
    
  191.         The subselect works and returns results equivalent to a
    
  192.         query with the IDs listed.
    
  193. 
    
  194.         Before the corresponding fix for this bug, this test passed in 1.1 and
    
  195.         failed in 1.2-beta (trunk).
    
  196.         """
    
  197.         qs = Book.objects.values("contact").annotate(Max("id"))
    
  198.         qs = qs.order_by("contact").values_list("id__max", flat=True)
    
  199.         # don't do anything with the queryset (qs) before including it as a
    
  200.         # subquery
    
  201.         books = Book.objects.order_by("id")
    
  202.         qs1 = books.filter(id__in=qs)
    
  203.         qs2 = books.filter(id__in=list(qs))
    
  204.         self.assertEqual(list(qs1), list(qs2))
    
  205. 
    
  206.     def test_aggregates_in_where_clause_pre_eval(self):
    
  207.         """
    
  208.         Regression test for #12822: DatabaseError: aggregates not allowed in
    
  209.         WHERE clause
    
  210. 
    
  211.         Same as the above test, but evaluates the queryset for the subquery
    
  212.         before it's used as a subquery.
    
  213. 
    
  214.         Before the corresponding fix for this bug, this test failed in both
    
  215.         1.1 and 1.2-beta (trunk).
    
  216.         """
    
  217.         qs = Book.objects.values("contact").annotate(Max("id"))
    
  218.         qs = qs.order_by("contact").values_list("id__max", flat=True)
    
  219.         # force the queryset (qs) for the subquery to be evaluated in its
    
  220.         # current state
    
  221.         list(qs)
    
  222.         books = Book.objects.order_by("id")
    
  223.         qs1 = books.filter(id__in=qs)
    
  224.         qs2 = books.filter(id__in=list(qs))
    
  225.         self.assertEqual(list(qs1), list(qs2))
    
  226. 
    
  227.     @skipUnlessDBFeature("supports_subqueries_in_group_by")
    
  228.     def test_annotate_with_extra(self):
    
  229.         """
    
  230.         Regression test for #11916: Extra params + aggregation creates
    
  231.         incorrect SQL.
    
  232.         """
    
  233.         # Oracle doesn't support subqueries in group by clause
    
  234.         shortest_book_sql = """
    
  235.         SELECT name
    
  236.         FROM aggregation_regress_book b
    
  237.         WHERE b.publisher_id = aggregation_regress_publisher.id
    
  238.         ORDER BY b.pages
    
  239.         LIMIT 1
    
  240.         """
    
  241.         # tests that this query does not raise a DatabaseError due to the full
    
  242.         # subselect being (erroneously) added to the GROUP BY parameters
    
  243.         qs = Publisher.objects.extra(
    
  244.             select={
    
  245.                 "name_of_shortest_book": shortest_book_sql,
    
  246.             }
    
  247.         ).annotate(total_books=Count("book"))
    
  248.         # force execution of the query
    
  249.         list(qs)
    
  250. 
    
  251.     def test_aggregate(self):
    
  252.         # Ordering requests are ignored
    
  253.         self.assertEqual(
    
  254.             Author.objects.order_by("name").aggregate(Avg("age")),
    
  255.             {"age__avg": Approximate(37.444, places=1)},
    
  256.         )
    
  257. 
    
  258.         # Implicit ordering is also ignored
    
  259.         self.assertEqual(
    
  260.             Book.objects.aggregate(Sum("pages")),
    
  261.             {"pages__sum": 3703},
    
  262.         )
    
  263. 
    
  264.         # Baseline results
    
  265.         self.assertEqual(
    
  266.             Book.objects.aggregate(Sum("pages"), Avg("pages")),
    
  267.             {"pages__sum": 3703, "pages__avg": Approximate(617.166, places=2)},
    
  268.         )
    
  269. 
    
  270.         # Empty values query doesn't affect grouping or results
    
  271.         self.assertEqual(
    
  272.             Book.objects.values().aggregate(Sum("pages"), Avg("pages")),
    
  273.             {"pages__sum": 3703, "pages__avg": Approximate(617.166, places=2)},
    
  274.         )
    
  275. 
    
  276.         # Aggregate overrides extra selected column
    
  277.         self.assertEqual(
    
  278.             Book.objects.extra(select={"price_per_page": "price / pages"}).aggregate(
    
  279.                 Sum("pages")
    
  280.             ),
    
  281.             {"pages__sum": 3703},
    
  282.         )
    
  283. 
    
  284.     def test_annotation(self):
    
  285.         # Annotations get combined with extra select clauses
    
  286.         obj = (
    
  287.             Book.objects.annotate(mean_auth_age=Avg("authors__age"))
    
  288.             .extra(select={"manufacture_cost": "price * .5"})
    
  289.             .get(pk=self.b2.pk)
    
  290.         )
    
  291.         self.assertObjectAttrs(
    
  292.             obj,
    
  293.             contact_id=self.a3.id,
    
  294.             isbn="067232959",
    
  295.             mean_auth_age=45.0,
    
  296.             name="Sams Teach Yourself Django in 24 Hours",
    
  297.             pages=528,
    
  298.             price=Decimal("23.09"),
    
  299.             pubdate=datetime.date(2008, 3, 3),
    
  300.             publisher_id=self.p2.id,
    
  301.             rating=3.0,
    
  302.         )
    
  303.         # Different DB backends return different types for the extra select computation
    
  304.         self.assertIn(obj.manufacture_cost, (11.545, Decimal("11.545")))
    
  305. 
    
  306.         # Order of the annotate/extra in the query doesn't matter
    
  307.         obj = (
    
  308.             Book.objects.extra(select={"manufacture_cost": "price * .5"})
    
  309.             .annotate(mean_auth_age=Avg("authors__age"))
    
  310.             .get(pk=self.b2.pk)
    
  311.         )
    
  312.         self.assertObjectAttrs(
    
  313.             obj,
    
  314.             contact_id=self.a3.id,
    
  315.             isbn="067232959",
    
  316.             mean_auth_age=45.0,
    
  317.             name="Sams Teach Yourself Django in 24 Hours",
    
  318.             pages=528,
    
  319.             price=Decimal("23.09"),
    
  320.             pubdate=datetime.date(2008, 3, 3),
    
  321.             publisher_id=self.p2.id,
    
  322.             rating=3.0,
    
  323.         )
    
  324.         # Different DB backends return different types for the extra select computation
    
  325.         self.assertIn(obj.manufacture_cost, (11.545, Decimal("11.545")))
    
  326. 
    
  327.         # Values queries can be combined with annotate and extra
    
  328.         obj = (
    
  329.             Book.objects.annotate(mean_auth_age=Avg("authors__age"))
    
  330.             .extra(select={"manufacture_cost": "price * .5"})
    
  331.             .values()
    
  332.             .get(pk=self.b2.pk)
    
  333.         )
    
  334.         manufacture_cost = obj["manufacture_cost"]
    
  335.         self.assertIn(manufacture_cost, (11.545, Decimal("11.545")))
    
  336.         del obj["manufacture_cost"]
    
  337.         self.assertEqual(
    
  338.             obj,
    
  339.             {
    
  340.                 "id": self.b2.id,
    
  341.                 "contact_id": self.a3.id,
    
  342.                 "isbn": "067232959",
    
  343.                 "mean_auth_age": 45.0,
    
  344.                 "name": "Sams Teach Yourself Django in 24 Hours",
    
  345.                 "pages": 528,
    
  346.                 "price": Decimal("23.09"),
    
  347.                 "pubdate": datetime.date(2008, 3, 3),
    
  348.                 "publisher_id": self.p2.id,
    
  349.                 "rating": 3.0,
    
  350.             },
    
  351.         )
    
  352. 
    
  353.         # The order of the (empty) values, annotate and extra clauses doesn't
    
  354.         # matter
    
  355.         obj = (
    
  356.             Book.objects.values()
    
  357.             .annotate(mean_auth_age=Avg("authors__age"))
    
  358.             .extra(select={"manufacture_cost": "price * .5"})
    
  359.             .get(pk=self.b2.pk)
    
  360.         )
    
  361.         manufacture_cost = obj["manufacture_cost"]
    
  362.         self.assertIn(manufacture_cost, (11.545, Decimal("11.545")))
    
  363.         del obj["manufacture_cost"]
    
  364.         self.assertEqual(
    
  365.             obj,
    
  366.             {
    
  367.                 "id": self.b2.id,
    
  368.                 "contact_id": self.a3.id,
    
  369.                 "isbn": "067232959",
    
  370.                 "mean_auth_age": 45.0,
    
  371.                 "name": "Sams Teach Yourself Django in 24 Hours",
    
  372.                 "pages": 528,
    
  373.                 "price": Decimal("23.09"),
    
  374.                 "pubdate": datetime.date(2008, 3, 3),
    
  375.                 "publisher_id": self.p2.id,
    
  376.                 "rating": 3.0,
    
  377.             },
    
  378.         )
    
  379. 
    
  380.         # If the annotation precedes the values clause, it won't be included
    
  381.         # unless it is explicitly named
    
  382.         obj = (
    
  383.             Book.objects.annotate(mean_auth_age=Avg("authors__age"))
    
  384.             .extra(select={"price_per_page": "price / pages"})
    
  385.             .values("name")
    
  386.             .get(pk=self.b1.pk)
    
  387.         )
    
  388.         self.assertEqual(
    
  389.             obj,
    
  390.             {
    
  391.                 "name": "The Definitive Guide to Django: Web Development Done Right",
    
  392.             },
    
  393.         )
    
  394. 
    
  395.         obj = (
    
  396.             Book.objects.annotate(mean_auth_age=Avg("authors__age"))
    
  397.             .extra(select={"price_per_page": "price / pages"})
    
  398.             .values("name", "mean_auth_age")
    
  399.             .get(pk=self.b1.pk)
    
  400.         )
    
  401.         self.assertEqual(
    
  402.             obj,
    
  403.             {
    
  404.                 "mean_auth_age": 34.5,
    
  405.                 "name": "The Definitive Guide to Django: Web Development Done Right",
    
  406.             },
    
  407.         )
    
  408. 
    
  409.         # If an annotation isn't included in the values, it can still be used
    
  410.         # in a filter
    
  411.         qs = (
    
  412.             Book.objects.annotate(n_authors=Count("authors"))
    
  413.             .values("name")
    
  414.             .filter(n_authors__gt=2)
    
  415.         )
    
  416.         self.assertSequenceEqual(
    
  417.             qs,
    
  418.             [{"name": "Python Web Development with Django"}],
    
  419.         )
    
  420. 
    
  421.         # The annotations are added to values output if values() precedes
    
  422.         # annotate()
    
  423.         obj = (
    
  424.             Book.objects.values("name")
    
  425.             .annotate(mean_auth_age=Avg("authors__age"))
    
  426.             .extra(select={"price_per_page": "price / pages"})
    
  427.             .get(pk=self.b1.pk)
    
  428.         )
    
  429.         self.assertEqual(
    
  430.             obj,
    
  431.             {
    
  432.                 "mean_auth_age": 34.5,
    
  433.                 "name": "The Definitive Guide to Django: Web Development Done Right",
    
  434.             },
    
  435.         )
    
  436. 
    
  437.         # All of the objects are getting counted (allow_nulls) and that values
    
  438.         # respects the amount of objects
    
  439.         self.assertEqual(len(Author.objects.annotate(Avg("friends__age")).values()), 9)
    
  440. 
    
  441.         # Consecutive calls to annotate accumulate in the query
    
  442.         qs = (
    
  443.             Book.objects.values("price")
    
  444.             .annotate(oldest=Max("authors__age"))
    
  445.             .order_by("oldest", "price")
    
  446.             .annotate(Max("publisher__num_awards"))
    
  447.         )
    
  448.         self.assertSequenceEqual(
    
  449.             qs,
    
  450.             [
    
  451.                 {"price": Decimal("30"), "oldest": 35, "publisher__num_awards__max": 3},
    
  452.                 {
    
  453.                     "price": Decimal("29.69"),
    
  454.                     "oldest": 37,
    
  455.                     "publisher__num_awards__max": 7,
    
  456.                 },
    
  457.                 {
    
  458.                     "price": Decimal("23.09"),
    
  459.                     "oldest": 45,
    
  460.                     "publisher__num_awards__max": 1,
    
  461.                 },
    
  462.                 {"price": Decimal("75"), "oldest": 57, "publisher__num_awards__max": 9},
    
  463.                 {
    
  464.                     "price": Decimal("82.8"),
    
  465.                     "oldest": 57,
    
  466.                     "publisher__num_awards__max": 7,
    
  467.                 },
    
  468.             ],
    
  469.         )
    
  470. 
    
  471.     def test_aggregate_annotation(self):
    
  472.         # Aggregates can be composed over annotations.
    
  473.         # The return type is derived from the composed aggregate
    
  474.         vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate(
    
  475.             Max("pages"), Max("price"), Sum("num_authors"), Avg("num_authors")
    
  476.         )
    
  477.         self.assertEqual(
    
  478.             vals,
    
  479.             {
    
  480.                 "num_authors__sum": 10,
    
  481.                 "num_authors__avg": Approximate(1.666, places=2),
    
  482.                 "pages__max": 1132,
    
  483.                 "price__max": Decimal("82.80"),
    
  484.             },
    
  485.         )
    
  486. 
    
  487.         # Regression for #15624 - Missing SELECT columns when using values, annotate
    
  488.         # and aggregate in a single query
    
  489.         self.assertEqual(
    
  490.             Book.objects.annotate(c=Count("authors")).values("c").aggregate(Max("c")),
    
  491.             {"c__max": 3},
    
  492.         )
    
  493. 
    
  494.     def test_conditional_aggregate(self):
    
  495.         # Conditional aggregation of a grouped queryset.
    
  496.         self.assertEqual(
    
  497.             Book.objects.annotate(c=Count("authors"))
    
  498.             .values("pk")
    
  499.             .aggregate(test=Sum(Case(When(c__gt=1, then=1))))["test"],
    
  500.             3,
    
  501.         )
    
  502. 
    
  503.     def test_sliced_conditional_aggregate(self):
    
  504.         self.assertEqual(
    
  505.             Author.objects.order_by("pk")[:5].aggregate(
    
  506.                 test=Sum(Case(When(age__lte=35, then=1)))
    
  507.             )["test"],
    
  508.             3,
    
  509.         )
    
  510. 
    
  511.     def test_annotated_conditional_aggregate(self):
    
  512.         annotated_qs = Book.objects.annotate(
    
  513.             discount_price=F("price") * Decimal("0.75")
    
  514.         )
    
  515.         self.assertAlmostEqual(
    
  516.             annotated_qs.aggregate(
    
  517.                 test=Avg(
    
  518.                     Case(
    
  519.                         When(pages__lt=400, then="discount_price"),
    
  520.                         output_field=DecimalField(),
    
  521.                     )
    
  522.                 )
    
  523.             )["test"],
    
  524.             Decimal("22.27"),
    
  525.             places=2,
    
  526.         )
    
  527. 
    
  528.     def test_distinct_conditional_aggregate(self):
    
  529.         self.assertEqual(
    
  530.             Book.objects.distinct().aggregate(
    
  531.                 test=Avg(
    
  532.                     Case(
    
  533.                         When(price=Decimal("29.69"), then="pages"),
    
  534.                         output_field=IntegerField(),
    
  535.                     )
    
  536.                 )
    
  537.             )["test"],
    
  538.             325,
    
  539.         )
    
  540. 
    
  541.     def test_conditional_aggregate_on_complex_condition(self):
    
  542.         self.assertEqual(
    
  543.             Book.objects.distinct().aggregate(
    
  544.                 test=Avg(
    
  545.                     Case(
    
  546.                         When(
    
  547.                             Q(price__gte=Decimal("29")) & Q(price__lt=Decimal("30")),
    
  548.                             then="pages",
    
  549.                         ),
    
  550.                         output_field=IntegerField(),
    
  551.                     )
    
  552.                 )
    
  553.             )["test"],
    
  554.             325,
    
  555.         )
    
  556. 
    
  557.     def test_decimal_aggregate_annotation_filter(self):
    
  558.         """
    
  559.         Filtering on an aggregate annotation with Decimal values should work.
    
  560.         Requires special handling on SQLite (#18247).
    
  561.         """
    
  562.         self.assertEqual(
    
  563.             len(
    
  564.                 Author.objects.annotate(sum=Sum("book_contact_set__price")).filter(
    
  565.                     sum__gt=Decimal(40)
    
  566.                 )
    
  567.             ),
    
  568.             1,
    
  569.         )
    
  570.         self.assertEqual(
    
  571.             len(
    
  572.                 Author.objects.annotate(sum=Sum("book_contact_set__price")).filter(
    
  573.                     sum__lte=Decimal(40)
    
  574.                 )
    
  575.             ),
    
  576.             4,
    
  577.         )
    
  578. 
    
  579.     def test_field_error(self):
    
  580.         # Bad field requests in aggregates are caught and reported
    
  581.         msg = (
    
  582.             "Cannot resolve keyword 'foo' into field. Choices are: authors, "
    
  583.             "contact, contact_id, hardbackbook, id, isbn, name, pages, price, "
    
  584.             "pubdate, publisher, publisher_id, rating, store, tags"
    
  585.         )
    
  586.         with self.assertRaisesMessage(FieldError, msg):
    
  587.             Book.objects.aggregate(num_authors=Count("foo"))
    
  588. 
    
  589.         with self.assertRaisesMessage(FieldError, msg):
    
  590.             Book.objects.annotate(num_authors=Count("foo"))
    
  591. 
    
  592.         msg = (
    
  593.             "Cannot resolve keyword 'foo' into field. Choices are: authors, "
    
  594.             "contact, contact_id, hardbackbook, id, isbn, name, num_authors, "
    
  595.             "pages, price, pubdate, publisher, publisher_id, rating, store, tags"
    
  596.         )
    
  597.         with self.assertRaisesMessage(FieldError, msg):
    
  598.             Book.objects.annotate(num_authors=Count("authors__id")).aggregate(
    
  599.                 Max("foo")
    
  600.             )
    
  601. 
    
  602.     def test_more(self):
    
  603.         # Old-style count aggregations can be mixed with new-style
    
  604.         self.assertEqual(Book.objects.annotate(num_authors=Count("authors")).count(), 6)
    
  605. 
    
  606.         # Non-ordinal, non-computed Aggregates over annotations correctly
    
  607.         # inherit the annotation's internal type if the annotation is ordinal
    
  608.         # or computed
    
  609.         vals = Book.objects.annotate(num_authors=Count("authors")).aggregate(
    
  610.             Max("num_authors")
    
  611.         )
    
  612.         self.assertEqual(vals, {"num_authors__max": 3})
    
  613. 
    
  614.         vals = Publisher.objects.annotate(avg_price=Avg("book__price")).aggregate(
    
  615.             Max("avg_price")
    
  616.         )
    
  617.         self.assertEqual(vals, {"avg_price__max": 75.0})
    
  618. 
    
  619.         # Aliases are quoted to protected aliases that might be reserved names
    
  620.         vals = Book.objects.aggregate(number=Max("pages"), select=Max("pages"))
    
  621.         self.assertEqual(vals, {"number": 1132, "select": 1132})
    
  622. 
    
  623.         # Regression for #10064: select_related() plays nice with aggregates
    
  624.         obj = (
    
  625.             Book.objects.select_related("publisher")
    
  626.             .annotate(num_authors=Count("authors"))
    
  627.             .values()
    
  628.             .get(isbn="013790395")
    
  629.         )
    
  630.         self.assertEqual(
    
  631.             obj,
    
  632.             {
    
  633.                 "contact_id": self.a8.id,
    
  634.                 "id": self.b5.id,
    
  635.                 "isbn": "013790395",
    
  636.                 "name": "Artificial Intelligence: A Modern Approach",
    
  637.                 "num_authors": 2,
    
  638.                 "pages": 1132,
    
  639.                 "price": Decimal("82.8"),
    
  640.                 "pubdate": datetime.date(1995, 1, 15),
    
  641.                 "publisher_id": self.p3.id,
    
  642.                 "rating": 4.0,
    
  643.             },
    
  644.         )
    
  645. 
    
  646.         # Regression for #10010: exclude on an aggregate field is correctly
    
  647.         # negated
    
  648.         self.assertEqual(len(Book.objects.annotate(num_authors=Count("authors"))), 6)
    
  649.         self.assertEqual(
    
  650.             len(
    
  651.                 Book.objects.annotate(num_authors=Count("authors")).filter(
    
  652.                     num_authors__gt=2
    
  653.                 )
    
  654.             ),
    
  655.             1,
    
  656.         )
    
  657.         self.assertEqual(
    
  658.             len(
    
  659.                 Book.objects.annotate(num_authors=Count("authors")).exclude(
    
  660.                     num_authors__gt=2
    
  661.                 )
    
  662.             ),
    
  663.             5,
    
  664.         )
    
  665. 
    
  666.         self.assertEqual(
    
  667.             len(
    
  668.                 Book.objects.annotate(num_authors=Count("authors"))
    
  669.                 .filter(num_authors__lt=3)
    
  670.                 .exclude(num_authors__lt=2)
    
  671.             ),
    
  672.             2,
    
  673.         )
    
  674.         self.assertEqual(
    
  675.             len(
    
  676.                 Book.objects.annotate(num_authors=Count("authors"))
    
  677.                 .exclude(num_authors__lt=2)
    
  678.                 .filter(num_authors__lt=3)
    
  679.             ),
    
  680.             2,
    
  681.         )
    
  682. 
    
  683.     def test_aggregate_fexpr(self):
    
  684.         # Aggregates can be used with F() expressions
    
  685.         # ... where the F() is pushed into the HAVING clause
    
  686.         qs = (
    
  687.             Publisher.objects.annotate(num_books=Count("book"))
    
  688.             .filter(num_books__lt=F("num_awards") / 2)
    
  689.             .order_by("name")
    
  690.             .values("name", "num_books", "num_awards")
    
  691.         )
    
  692.         self.assertSequenceEqual(
    
  693.             qs,
    
  694.             [
    
  695.                 {"num_books": 1, "name": "Morgan Kaufmann", "num_awards": 9},
    
  696.                 {"num_books": 2, "name": "Prentice Hall", "num_awards": 7},
    
  697.             ],
    
  698.         )
    
  699. 
    
  700.         qs = (
    
  701.             Publisher.objects.annotate(num_books=Count("book"))
    
  702.             .exclude(num_books__lt=F("num_awards") / 2)
    
  703.             .order_by("name")
    
  704.             .values("name", "num_books", "num_awards")
    
  705.         )
    
  706.         self.assertSequenceEqual(
    
  707.             qs,
    
  708.             [
    
  709.                 {"num_books": 2, "name": "Apress", "num_awards": 3},
    
  710.                 {"num_books": 0, "name": "Jonno's House of Books", "num_awards": 0},
    
  711.                 {"num_books": 1, "name": "Sams", "num_awards": 1},
    
  712.             ],
    
  713.         )
    
  714. 
    
  715.         # ... and where the F() references an aggregate
    
  716.         qs = (
    
  717.             Publisher.objects.annotate(num_books=Count("book"))
    
  718.             .filter(num_awards__gt=2 * F("num_books"))
    
  719.             .order_by("name")
    
  720.             .values("name", "num_books", "num_awards")
    
  721.         )
    
  722.         self.assertSequenceEqual(
    
  723.             qs,
    
  724.             [
    
  725.                 {"num_books": 1, "name": "Morgan Kaufmann", "num_awards": 9},
    
  726.                 {"num_books": 2, "name": "Prentice Hall", "num_awards": 7},
    
  727.             ],
    
  728.         )
    
  729. 
    
  730.         qs = (
    
  731.             Publisher.objects.annotate(num_books=Count("book"))
    
  732.             .exclude(num_books__lt=F("num_awards") / 2)
    
  733.             .order_by("name")
    
  734.             .values("name", "num_books", "num_awards")
    
  735.         )
    
  736.         self.assertSequenceEqual(
    
  737.             qs,
    
  738.             [
    
  739.                 {"num_books": 2, "name": "Apress", "num_awards": 3},
    
  740.                 {"num_books": 0, "name": "Jonno's House of Books", "num_awards": 0},
    
  741.                 {"num_books": 1, "name": "Sams", "num_awards": 1},
    
  742.             ],
    
  743.         )
    
  744. 
    
  745.     def test_db_col_table(self):
    
  746.         # Tests on fields with non-default table and column names.
    
  747.         qs = Clues.objects.values("EntryID__Entry").annotate(
    
  748.             Appearances=Count("EntryID"), Distinct_Clues=Count("Clue", distinct=True)
    
  749.         )
    
  750.         self.assertQuerysetEqual(qs, [])
    
  751. 
    
  752.         qs = Entries.objects.annotate(clue_count=Count("clues__ID"))
    
  753.         self.assertQuerysetEqual(qs, [])
    
  754. 
    
  755.     def test_boolean_conversion(self):
    
  756.         # Aggregates mixed up ordering of columns for backend's convert_values
    
  757.         # method. Refs #21126.
    
  758.         e = Entries.objects.create(Entry="foo")
    
  759.         c = Clues.objects.create(EntryID=e, Clue="bar")
    
  760.         qs = Clues.objects.select_related("EntryID").annotate(Count("ID"))
    
  761.         self.assertSequenceEqual(qs, [c])
    
  762.         self.assertEqual(qs[0].EntryID, e)
    
  763.         self.assertIs(qs[0].EntryID.Exclude, False)
    
  764. 
    
  765.     def test_empty(self):
    
  766.         # Regression for #10089: Check handling of empty result sets with
    
  767.         # aggregates
    
  768.         self.assertEqual(Book.objects.filter(id__in=[]).count(), 0)
    
  769. 
    
  770.         vals = Book.objects.filter(id__in=[]).aggregate(
    
  771.             num_authors=Count("authors"),
    
  772.             avg_authors=Avg("authors"),
    
  773.             max_authors=Max("authors"),
    
  774.             max_price=Max("price"),
    
  775.             max_rating=Max("rating"),
    
  776.         )
    
  777.         self.assertEqual(
    
  778.             vals,
    
  779.             {
    
  780.                 "max_authors": None,
    
  781.                 "max_rating": None,
    
  782.                 "num_authors": 0,
    
  783.                 "avg_authors": None,
    
  784.                 "max_price": None,
    
  785.             },
    
  786.         )
    
  787. 
    
  788.         qs = (
    
  789.             Publisher.objects.filter(name="Jonno's House of Books")
    
  790.             .annotate(
    
  791.                 num_authors=Count("book__authors"),
    
  792.                 avg_authors=Avg("book__authors"),
    
  793.                 max_authors=Max("book__authors"),
    
  794.                 max_price=Max("book__price"),
    
  795.                 max_rating=Max("book__rating"),
    
  796.             )
    
  797.             .values()
    
  798.         )
    
  799.         self.assertSequenceEqual(
    
  800.             qs,
    
  801.             [
    
  802.                 {
    
  803.                     "max_authors": None,
    
  804.                     "name": "Jonno's House of Books",
    
  805.                     "num_awards": 0,
    
  806.                     "max_price": None,
    
  807.                     "num_authors": 0,
    
  808.                     "max_rating": None,
    
  809.                     "id": self.p5.id,
    
  810.                     "avg_authors": None,
    
  811.                 }
    
  812.             ],
    
  813.         )
    
  814. 
    
  815.     def test_more_more(self):
    
  816.         # Regression for #10113 - Fields mentioned in order_by() must be
    
  817.         # included in the GROUP BY. This only becomes a problem when the
    
  818.         # order_by introduces a new join.
    
  819.         self.assertQuerysetEqual(
    
  820.             Book.objects.annotate(num_authors=Count("authors")).order_by(
    
  821.                 "publisher__name", "name"
    
  822.             ),
    
  823.             [
    
  824.                 "Practical Django Projects",
    
  825.                 "The Definitive Guide to Django: Web Development Done Right",
    
  826.                 "Paradigms of Artificial Intelligence Programming: Case Studies in "
    
  827.                 "Common Lisp",
    
  828.                 "Artificial Intelligence: A Modern Approach",
    
  829.                 "Python Web Development with Django",
    
  830.                 "Sams Teach Yourself Django in 24 Hours",
    
  831.             ],
    
  832.             lambda b: b.name,
    
  833.         )
    
  834. 
    
  835.         # Regression for #10127 - Empty select_related() works with annotate
    
  836.         qs = (
    
  837.             Book.objects.filter(rating__lt=4.5)
    
  838.             .select_related()
    
  839.             .annotate(Avg("authors__age"))
    
  840.             .order_by("name")
    
  841.         )
    
  842.         self.assertQuerysetEqual(
    
  843.             qs,
    
  844.             [
    
  845.                 (
    
  846.                     "Artificial Intelligence: A Modern Approach",
    
  847.                     51.5,
    
  848.                     "Prentice Hall",
    
  849.                     "Peter Norvig",
    
  850.                 ),
    
  851.                 ("Practical Django Projects", 29.0, "Apress", "James Bennett"),
    
  852.                 (
    
  853.                     "Python Web Development with Django",
    
  854.                     Approximate(30.333, places=2),
    
  855.                     "Prentice Hall",
    
  856.                     "Jeffrey Forcier",
    
  857.                 ),
    
  858.                 ("Sams Teach Yourself Django in 24 Hours", 45.0, "Sams", "Brad Dayley"),
    
  859.             ],
    
  860.             lambda b: (b.name, b.authors__age__avg, b.publisher.name, b.contact.name),
    
  861.         )
    
  862. 
    
  863.         # Regression for #10132 - If the values() clause only mentioned extra
    
  864.         # (select=) columns, those columns are used for grouping
    
  865.         qs = (
    
  866.             Book.objects.extra(select={"pub": "publisher_id"})
    
  867.             .values("pub")
    
  868.             .annotate(Count("id"))
    
  869.             .order_by("pub")
    
  870.         )
    
  871.         self.assertSequenceEqual(
    
  872.             qs,
    
  873.             [
    
  874.                 {"pub": self.p1.id, "id__count": 2},
    
  875.                 {"pub": self.p2.id, "id__count": 1},
    
  876.                 {"pub": self.p3.id, "id__count": 2},
    
  877.                 {"pub": self.p4.id, "id__count": 1},
    
  878.             ],
    
  879.         )
    
  880. 
    
  881.         qs = (
    
  882.             Book.objects.extra(select={"pub": "publisher_id", "foo": "pages"})
    
  883.             .values("pub")
    
  884.             .annotate(Count("id"))
    
  885.             .order_by("pub")
    
  886.         )
    
  887.         self.assertSequenceEqual(
    
  888.             qs,
    
  889.             [
    
  890.                 {"pub": self.p1.id, "id__count": 2},
    
  891.                 {"pub": self.p2.id, "id__count": 1},
    
  892.                 {"pub": self.p3.id, "id__count": 2},
    
  893.                 {"pub": self.p4.id, "id__count": 1},
    
  894.             ],
    
  895.         )
    
  896. 
    
  897.         # Regression for #10182 - Queries with aggregate calls are correctly
    
  898.         # realiased when used in a subquery
    
  899.         ids = (
    
  900.             Book.objects.filter(pages__gt=100)
    
  901.             .annotate(n_authors=Count("authors"))
    
  902.             .filter(n_authors__gt=2)
    
  903.             .order_by("n_authors")
    
  904.         )
    
  905.         self.assertQuerysetEqual(
    
  906.             Book.objects.filter(id__in=ids),
    
  907.             [
    
  908.                 "Python Web Development with Django",
    
  909.             ],
    
  910.             lambda b: b.name,
    
  911.         )
    
  912. 
    
  913.         # Regression for #15709 - Ensure each group_by field only exists once
    
  914.         # per query
    
  915.         qstr = str(
    
  916.             Book.objects.values("publisher")
    
  917.             .annotate(max_pages=Max("pages"))
    
  918.             .order_by()
    
  919.             .query
    
  920.         )
    
  921.         # There is just one GROUP BY clause (zero commas means at most one clause).
    
  922.         self.assertEqual(qstr[qstr.index("GROUP BY") :].count(", "), 0)
    
  923. 
    
  924.     def test_duplicate_alias(self):
    
  925.         # Regression for #11256 - duplicating a default alias raises ValueError.
    
  926.         msg = (
    
  927.             "The named annotation 'authors__age__avg' conflicts with "
    
  928.             "the default name for another annotation."
    
  929.         )
    
  930.         with self.assertRaisesMessage(ValueError, msg):
    
  931.             Book.objects.annotate(
    
  932.                 Avg("authors__age"), authors__age__avg=Avg("authors__age")
    
  933.             )
    
  934. 
    
  935.     def test_field_name_conflict(self):
    
  936.         # Regression for #11256 - providing an aggregate name
    
  937.         # that conflicts with a field name on the model raises ValueError
    
  938.         msg = "The annotation 'age' conflicts with a field on the model."
    
  939.         with self.assertRaisesMessage(ValueError, msg):
    
  940.             Author.objects.annotate(age=Avg("friends__age"))
    
  941. 
    
  942.     def test_m2m_name_conflict(self):
    
  943.         # Regression for #11256 - providing an aggregate name
    
  944.         # that conflicts with an m2m name on the model raises ValueError
    
  945.         msg = "The annotation 'friends' conflicts with a field on the model."
    
  946.         with self.assertRaisesMessage(ValueError, msg):
    
  947.             Author.objects.annotate(friends=Count("friends"))
    
  948. 
    
  949.     def test_fk_attname_conflict(self):
    
  950.         msg = "The annotation 'contact_id' conflicts with a field on the model."
    
  951.         with self.assertRaisesMessage(ValueError, msg):
    
  952.             Book.objects.annotate(contact_id=F("publisher_id"))
    
  953. 
    
  954.     def test_values_queryset_non_conflict(self):
    
  955.         # If you're using a values query set, some potential conflicts are
    
  956.         # avoided.
    
  957.         # age is a field on Author, so it shouldn't be allowed as an aggregate.
    
  958.         # But age isn't included in values(), so it is.
    
  959.         results = (
    
  960.             Author.objects.values("name")
    
  961.             .annotate(age=Count("book_contact_set"))
    
  962.             .order_by("name")
    
  963.         )
    
  964.         self.assertEqual(len(results), 9)
    
  965.         self.assertEqual(results[0]["name"], "Adrian Holovaty")
    
  966.         self.assertEqual(results[0]["age"], 1)
    
  967. 
    
  968.         # Same problem, but aggregating over m2m fields
    
  969.         results = (
    
  970.             Author.objects.values("name")
    
  971.             .annotate(age=Avg("friends__age"))
    
  972.             .order_by("name")
    
  973.         )
    
  974.         self.assertEqual(len(results), 9)
    
  975.         self.assertEqual(results[0]["name"], "Adrian Holovaty")
    
  976.         self.assertEqual(results[0]["age"], 32.0)
    
  977. 
    
  978.         # Same problem, but colliding with an m2m field
    
  979.         results = (
    
  980.             Author.objects.values("name")
    
  981.             .annotate(friends=Count("friends"))
    
  982.             .order_by("name")
    
  983.         )
    
  984.         self.assertEqual(len(results), 9)
    
  985.         self.assertEqual(results[0]["name"], "Adrian Holovaty")
    
  986.         self.assertEqual(results[0]["friends"], 2)
    
  987. 
    
  988.     def test_reverse_relation_name_conflict(self):
    
  989.         # Regression for #11256 - providing an aggregate name
    
  990.         # that conflicts with a reverse-related name on the model raises ValueError
    
  991.         msg = "The annotation 'book_contact_set' conflicts with a field on the model."
    
  992.         with self.assertRaisesMessage(ValueError, msg):
    
  993.             Author.objects.annotate(book_contact_set=Avg("friends__age"))
    
  994. 
    
  995.     def test_pickle(self):
    
  996.         # Regression for #10197 -- Queries with aggregates can be pickled.
    
  997.         # First check that pickling is possible at all. No crash = success
    
  998.         qs = Book.objects.annotate(num_authors=Count("authors"))
    
  999.         pickle.dumps(qs)
    
  1000. 
    
  1001.         # Then check that the round trip works.
    
  1002.         query = qs.query.get_compiler(qs.db).as_sql()[0]
    
  1003.         qs2 = pickle.loads(pickle.dumps(qs))
    
  1004.         self.assertEqual(
    
  1005.             qs2.query.get_compiler(qs2.db).as_sql()[0],
    
  1006.             query,
    
  1007.         )
    
  1008. 
    
  1009.     def test_more_more_more(self):
    
  1010.         # Regression for #10199 - Aggregate calls clone the original query so
    
  1011.         # the original query can still be used
    
  1012.         books = Book.objects.all()
    
  1013.         books.aggregate(Avg("authors__age"))
    
  1014.         self.assertQuerysetEqual(
    
  1015.             books.all(),
    
  1016.             [
    
  1017.                 "Artificial Intelligence: A Modern Approach",
    
  1018.                 "Paradigms of Artificial Intelligence Programming: Case Studies in "
    
  1019.                 "Common Lisp",
    
  1020.                 "Practical Django Projects",
    
  1021.                 "Python Web Development with Django",
    
  1022.                 "Sams Teach Yourself Django in 24 Hours",
    
  1023.                 "The Definitive Guide to Django: Web Development Done Right",
    
  1024.             ],
    
  1025.             lambda b: b.name,
    
  1026.         )
    
  1027. 
    
  1028.         # Regression for #10248 - Annotations work with dates()
    
  1029.         qs = (
    
  1030.             Book.objects.annotate(num_authors=Count("authors"))
    
  1031.             .filter(num_authors=2)
    
  1032.             .dates("pubdate", "day")
    
  1033.         )
    
  1034.         self.assertSequenceEqual(
    
  1035.             qs,
    
  1036.             [
    
  1037.                 datetime.date(1995, 1, 15),
    
  1038.                 datetime.date(2007, 12, 6),
    
  1039.             ],
    
  1040.         )
    
  1041. 
    
  1042.         # Regression for #10290 - extra selects with parameters can be used for
    
  1043.         # grouping.
    
  1044.         qs = (
    
  1045.             Book.objects.annotate(mean_auth_age=Avg("authors__age"))
    
  1046.             .extra(select={"sheets": "(pages + %s) / %s"}, select_params=[1, 2])
    
  1047.             .order_by("sheets")
    
  1048.             .values("sheets")
    
  1049.         )
    
  1050.         self.assertQuerysetEqual(
    
  1051.             qs, [150, 175, 224, 264, 473, 566], lambda b: int(b["sheets"])
    
  1052.         )
    
  1053. 
    
  1054.         # Regression for 10425 - annotations don't get in the way of a count()
    
  1055.         # clause
    
  1056.         self.assertEqual(
    
  1057.             Book.objects.values("publisher").annotate(Count("publisher")).count(), 4
    
  1058.         )
    
  1059.         self.assertEqual(
    
  1060.             Book.objects.annotate(Count("publisher")).values("publisher").count(), 6
    
  1061.         )
    
  1062. 
    
  1063.         # Note: intentionally no order_by(), that case needs tests, too.
    
  1064.         publishers = Publisher.objects.filter(id__in=[self.p1.id, self.p2.id])
    
  1065.         self.assertEqual(sorted(p.name for p in publishers), ["Apress", "Sams"])
    
  1066. 
    
  1067.         publishers = publishers.annotate(n_books=Count("book"))
    
  1068.         sorted_publishers = sorted(publishers, key=lambda x: x.name)
    
  1069.         self.assertEqual(sorted_publishers[0].n_books, 2)
    
  1070.         self.assertEqual(sorted_publishers[1].n_books, 1)
    
  1071. 
    
  1072.         self.assertEqual(sorted(p.name for p in publishers), ["Apress", "Sams"])
    
  1073. 
    
  1074.         books = Book.objects.filter(publisher__in=publishers)
    
  1075.         self.assertQuerysetEqual(
    
  1076.             books,
    
  1077.             [
    
  1078.                 "Practical Django Projects",
    
  1079.                 "Sams Teach Yourself Django in 24 Hours",
    
  1080.                 "The Definitive Guide to Django: Web Development Done Right",
    
  1081.             ],
    
  1082.             lambda b: b.name,
    
  1083.         )
    
  1084.         self.assertEqual(sorted(p.name for p in publishers), ["Apress", "Sams"])
    
  1085. 
    
  1086.         # Regression for 10666 - inherited fields work with annotations and
    
  1087.         # aggregations
    
  1088.         self.assertEqual(
    
  1089.             HardbackBook.objects.aggregate(n_pages=Sum("book_ptr__pages")),
    
  1090.             {"n_pages": 2078},
    
  1091.         )
    
  1092. 
    
  1093.         self.assertEqual(
    
  1094.             HardbackBook.objects.aggregate(n_pages=Sum("pages")),
    
  1095.             {"n_pages": 2078},
    
  1096.         )
    
  1097. 
    
  1098.         qs = (
    
  1099.             HardbackBook.objects.annotate(
    
  1100.                 n_authors=Count("book_ptr__authors"),
    
  1101.             )
    
  1102.             .values("name", "n_authors")
    
  1103.             .order_by("name")
    
  1104.         )
    
  1105.         self.assertSequenceEqual(
    
  1106.             qs,
    
  1107.             [
    
  1108.                 {"n_authors": 2, "name": "Artificial Intelligence: A Modern Approach"},
    
  1109.                 {
    
  1110.                     "n_authors": 1,
    
  1111.                     "name": (
    
  1112.                         "Paradigms of Artificial Intelligence Programming: Case "
    
  1113.                         "Studies in Common Lisp"
    
  1114.                     ),
    
  1115.                 },
    
  1116.             ],
    
  1117.         )
    
  1118. 
    
  1119.         qs = (
    
  1120.             HardbackBook.objects.annotate(n_authors=Count("authors"))
    
  1121.             .values("name", "n_authors")
    
  1122.             .order_by("name")
    
  1123.         )
    
  1124.         self.assertSequenceEqual(
    
  1125.             qs,
    
  1126.             [
    
  1127.                 {"n_authors": 2, "name": "Artificial Intelligence: A Modern Approach"},
    
  1128.                 {
    
  1129.                     "n_authors": 1,
    
  1130.                     "name": (
    
  1131.                         "Paradigms of Artificial Intelligence Programming: Case "
    
  1132.                         "Studies in Common Lisp"
    
  1133.                     ),
    
  1134.                 },
    
  1135.             ],
    
  1136.         )
    
  1137. 
    
  1138.         # Regression for #10766 - Shouldn't be able to reference an aggregate
    
  1139.         # fields in an aggregate() call.
    
  1140.         msg = "Cannot compute Avg('mean_age'): 'mean_age' is an aggregate"
    
  1141.         with self.assertRaisesMessage(FieldError, msg):
    
  1142.             Book.objects.annotate(mean_age=Avg("authors__age")).annotate(
    
  1143.                 Avg("mean_age")
    
  1144.             )
    
  1145. 
    
  1146.     def test_empty_filter_count(self):
    
  1147.         self.assertEqual(
    
  1148.             Author.objects.filter(id__in=[]).annotate(Count("friends")).count(), 0
    
  1149.         )
    
  1150. 
    
  1151.     def test_empty_filter_aggregate(self):
    
  1152.         self.assertEqual(
    
  1153.             Author.objects.filter(id__in=[])
    
  1154.             .annotate(Count("friends"))
    
  1155.             .aggregate(Count("pk")),
    
  1156.             {"pk__count": 0},
    
  1157.         )
    
  1158. 
    
  1159.     def test_none_call_before_aggregate(self):
    
  1160.         # Regression for #11789
    
  1161.         self.assertEqual(
    
  1162.             Author.objects.none().aggregate(Avg("age")), {"age__avg": None}
    
  1163.         )
    
  1164. 
    
  1165.     def test_annotate_and_join(self):
    
  1166.         self.assertEqual(
    
  1167.             Author.objects.annotate(c=Count("friends__name"))
    
  1168.             .exclude(friends__name="Joe")
    
  1169.             .count(),
    
  1170.             Author.objects.count(),
    
  1171.         )
    
  1172. 
    
  1173.     def test_f_expression_annotation(self):
    
  1174.         # Books with less than 200 pages per author.
    
  1175.         qs = (
    
  1176.             Book.objects.values("name")
    
  1177.             .annotate(n_authors=Count("authors"))
    
  1178.             .filter(pages__lt=F("n_authors") * 200)
    
  1179.             .values_list("pk")
    
  1180.         )
    
  1181.         self.assertQuerysetEqual(
    
  1182.             Book.objects.filter(pk__in=qs),
    
  1183.             ["Python Web Development with Django"],
    
  1184.             attrgetter("name"),
    
  1185.         )
    
  1186. 
    
  1187.     def test_values_annotate_values(self):
    
  1188.         qs = (
    
  1189.             Book.objects.values("name")
    
  1190.             .annotate(n_authors=Count("authors"))
    
  1191.             .values_list("pk", flat=True)
    
  1192.             .order_by("name")
    
  1193.         )
    
  1194.         self.assertEqual(list(qs), list(Book.objects.values_list("pk", flat=True)))
    
  1195. 
    
  1196.     def test_having_group_by(self):
    
  1197.         # When a field occurs on the LHS of a HAVING clause that it
    
  1198.         # appears correctly in the GROUP BY clause
    
  1199.         qs = (
    
  1200.             Book.objects.values_list("name")
    
  1201.             .annotate(n_authors=Count("authors"))
    
  1202.             .filter(pages__gt=F("n_authors"))
    
  1203.             .values_list("name", flat=True)
    
  1204.             .order_by("name")
    
  1205.         )
    
  1206.         # Results should be the same, all Books have more pages than authors
    
  1207.         self.assertEqual(list(qs), list(Book.objects.values_list("name", flat=True)))
    
  1208. 
    
  1209.     def test_values_list_annotation_args_ordering(self):
    
  1210.         """
    
  1211.         Annotate *args ordering should be preserved in values_list results.
    
  1212.         **kwargs comes after *args.
    
  1213.         Regression test for #23659.
    
  1214.         """
    
  1215.         books = (
    
  1216.             Book.objects.values_list("publisher__name")
    
  1217.             .annotate(
    
  1218.                 Count("id"), Avg("price"), Avg("authors__age"), avg_pgs=Avg("pages")
    
  1219.             )
    
  1220.             .order_by("-publisher__name")
    
  1221.         )
    
  1222.         self.assertEqual(books[0], ("Sams", 1, Decimal("23.09"), 45.0, 528.0))
    
  1223. 
    
  1224.     def test_annotation_disjunction(self):
    
  1225.         qs = (
    
  1226.             Book.objects.annotate(n_authors=Count("authors"))
    
  1227.             .filter(Q(n_authors=2) | Q(name="Python Web Development with Django"))
    
  1228.             .order_by("name")
    
  1229.         )
    
  1230.         self.assertQuerysetEqual(
    
  1231.             qs,
    
  1232.             [
    
  1233.                 "Artificial Intelligence: A Modern Approach",
    
  1234.                 "Python Web Development with Django",
    
  1235.                 "The Definitive Guide to Django: Web Development Done Right",
    
  1236.             ],
    
  1237.             attrgetter("name"),
    
  1238.         )
    
  1239. 
    
  1240.         qs = (
    
  1241.             Book.objects.annotate(n_authors=Count("authors")).filter(
    
  1242.                 Q(name="The Definitive Guide to Django: Web Development Done Right")
    
  1243.                 | (
    
  1244.                     Q(name="Artificial Intelligence: A Modern Approach")
    
  1245.                     & Q(n_authors=3)
    
  1246.                 )
    
  1247.             )
    
  1248.         ).order_by("name")
    
  1249.         self.assertQuerysetEqual(
    
  1250.             qs,
    
  1251.             [
    
  1252.                 "The Definitive Guide to Django: Web Development Done Right",
    
  1253.             ],
    
  1254.             attrgetter("name"),
    
  1255.         )
    
  1256. 
    
  1257.         qs = (
    
  1258.             Publisher.objects.annotate(
    
  1259.                 rating_sum=Sum("book__rating"), book_count=Count("book")
    
  1260.             )
    
  1261.             .filter(Q(rating_sum__gt=5.5) | Q(rating_sum__isnull=True))
    
  1262.             .order_by("pk")
    
  1263.         )
    
  1264.         self.assertQuerysetEqual(
    
  1265.             qs,
    
  1266.             [
    
  1267.                 "Apress",
    
  1268.                 "Prentice Hall",
    
  1269.                 "Jonno's House of Books",
    
  1270.             ],
    
  1271.             attrgetter("name"),
    
  1272.         )
    
  1273. 
    
  1274.         qs = (
    
  1275.             Publisher.objects.annotate(
    
  1276.                 rating_sum=Sum("book__rating"), book_count=Count("book")
    
  1277.             )
    
  1278.             .filter(Q(rating_sum__gt=F("book_count")) | Q(rating_sum=None))
    
  1279.             .order_by("num_awards")
    
  1280.         )
    
  1281.         self.assertQuerysetEqual(
    
  1282.             qs,
    
  1283.             [
    
  1284.                 "Jonno's House of Books",
    
  1285.                 "Sams",
    
  1286.                 "Apress",
    
  1287.                 "Prentice Hall",
    
  1288.                 "Morgan Kaufmann",
    
  1289.             ],
    
  1290.             attrgetter("name"),
    
  1291.         )
    
  1292. 
    
  1293.     def test_quoting_aggregate_order_by(self):
    
  1294.         qs = (
    
  1295.             Book.objects.filter(name="Python Web Development with Django")
    
  1296.             .annotate(authorCount=Count("authors"))
    
  1297.             .order_by("authorCount")
    
  1298.         )
    
  1299.         self.assertQuerysetEqual(
    
  1300.             qs,
    
  1301.             [
    
  1302.                 ("Python Web Development with Django", 3),
    
  1303.             ],
    
  1304.             lambda b: (b.name, b.authorCount),
    
  1305.         )
    
  1306. 
    
  1307.     def test_stddev(self):
    
  1308.         self.assertEqual(
    
  1309.             Book.objects.aggregate(StdDev("pages")),
    
  1310.             {"pages__stddev": Approximate(311.46, 1)},
    
  1311.         )
    
  1312. 
    
  1313.         self.assertEqual(
    
  1314.             Book.objects.aggregate(StdDev("rating")),
    
  1315.             {"rating__stddev": Approximate(0.60, 1)},
    
  1316.         )
    
  1317. 
    
  1318.         self.assertEqual(
    
  1319.             Book.objects.aggregate(StdDev("price")),
    
  1320.             {"price__stddev": Approximate(Decimal("24.16"), 2)},
    
  1321.         )
    
  1322. 
    
  1323.         self.assertEqual(
    
  1324.             Book.objects.aggregate(StdDev("pages", sample=True)),
    
  1325.             {"pages__stddev": Approximate(341.19, 2)},
    
  1326.         )
    
  1327. 
    
  1328.         self.assertEqual(
    
  1329.             Book.objects.aggregate(StdDev("rating", sample=True)),
    
  1330.             {"rating__stddev": Approximate(0.66, 2)},
    
  1331.         )
    
  1332. 
    
  1333.         self.assertEqual(
    
  1334.             Book.objects.aggregate(StdDev("price", sample=True)),
    
  1335.             {"price__stddev": Approximate(Decimal("26.46"), 1)},
    
  1336.         )
    
  1337. 
    
  1338.         self.assertEqual(
    
  1339.             Book.objects.aggregate(Variance("pages")),
    
  1340.             {"pages__variance": Approximate(97010.80, 1)},
    
  1341.         )
    
  1342. 
    
  1343.         self.assertEqual(
    
  1344.             Book.objects.aggregate(Variance("rating")),
    
  1345.             {"rating__variance": Approximate(0.36, 1)},
    
  1346.         )
    
  1347. 
    
  1348.         self.assertEqual(
    
  1349.             Book.objects.aggregate(Variance("price")),
    
  1350.             {"price__variance": Approximate(Decimal("583.77"), 1)},
    
  1351.         )
    
  1352. 
    
  1353.         self.assertEqual(
    
  1354.             Book.objects.aggregate(Variance("pages", sample=True)),
    
  1355.             {"pages__variance": Approximate(116412.96, 1)},
    
  1356.         )
    
  1357. 
    
  1358.         self.assertEqual(
    
  1359.             Book.objects.aggregate(Variance("rating", sample=True)),
    
  1360.             {"rating__variance": Approximate(0.44, 2)},
    
  1361.         )
    
  1362. 
    
  1363.         self.assertEqual(
    
  1364.             Book.objects.aggregate(Variance("price", sample=True)),
    
  1365.             {"price__variance": Approximate(Decimal("700.53"), 2)},
    
  1366.         )
    
  1367. 
    
  1368.     def test_filtering_by_annotation_name(self):
    
  1369.         # Regression test for #14476
    
  1370. 
    
  1371.         # The name of the explicitly provided annotation name in this case
    
  1372.         # poses no problem
    
  1373.         qs = (
    
  1374.             Author.objects.annotate(book_cnt=Count("book"))
    
  1375.             .filter(book_cnt=2)
    
  1376.             .order_by("name")
    
  1377.         )
    
  1378.         self.assertQuerysetEqual(qs, ["Peter Norvig"], lambda b: b.name)
    
  1379.         # Neither in this case
    
  1380.         qs = (
    
  1381.             Author.objects.annotate(book_count=Count("book"))
    
  1382.             .filter(book_count=2)
    
  1383.             .order_by("name")
    
  1384.         )
    
  1385.         self.assertQuerysetEqual(qs, ["Peter Norvig"], lambda b: b.name)
    
  1386.         # This case used to fail because the ORM couldn't resolve the
    
  1387.         # automatically generated annotation name `book__count`
    
  1388.         qs = (
    
  1389.             Author.objects.annotate(Count("book"))
    
  1390.             .filter(book__count=2)
    
  1391.             .order_by("name")
    
  1392.         )
    
  1393.         self.assertQuerysetEqual(qs, ["Peter Norvig"], lambda b: b.name)
    
  1394.         # Referencing the auto-generated name in an aggregate() also works.
    
  1395.         self.assertEqual(
    
  1396.             Author.objects.annotate(Count("book")).aggregate(Max("book__count")),
    
  1397.             {"book__count__max": 2},
    
  1398.         )
    
  1399. 
    
  1400.     def test_annotate_joins(self):
    
  1401.         """
    
  1402.         The base table's join isn't promoted to LOUTER. This could
    
  1403.         cause the query generation to fail if there is an exclude() for fk-field
    
  1404.         in the query, too. Refs #19087.
    
  1405.         """
    
  1406.         qs = Book.objects.annotate(n=Count("pk"))
    
  1407.         self.assertIs(qs.query.alias_map["aggregation_regress_book"].join_type, None)
    
  1408.         # The query executes without problems.
    
  1409.         self.assertEqual(len(qs.exclude(publisher=-1)), 6)
    
  1410. 
    
  1411.     @skipUnlessAnyDBFeature("allows_group_by_pk", "allows_group_by_selected_pks")
    
  1412.     def test_aggregate_duplicate_columns(self):
    
  1413.         # Regression test for #17144
    
  1414. 
    
  1415.         results = Author.objects.annotate(num_contacts=Count("book_contact_set"))
    
  1416. 
    
  1417.         # There should only be one GROUP BY clause, for the `id` column.
    
  1418.         # `name` and `age` should not be grouped on.
    
  1419.         _, _, group_by = results.query.get_compiler(using="default").pre_sql_setup()
    
  1420.         self.assertEqual(len(group_by), 1)
    
  1421.         self.assertIn("id", group_by[0][0])
    
  1422.         self.assertNotIn("name", group_by[0][0])
    
  1423.         self.assertNotIn("age", group_by[0][0])
    
  1424.         self.assertEqual(
    
  1425.             [(a.name, a.num_contacts) for a in results.order_by("name")],
    
  1426.             [
    
  1427.                 ("Adrian Holovaty", 1),
    
  1428.                 ("Brad Dayley", 1),
    
  1429.                 ("Jacob Kaplan-Moss", 0),
    
  1430.                 ("James Bennett", 1),
    
  1431.                 ("Jeffrey Forcier", 1),
    
  1432.                 ("Paul Bissex", 0),
    
  1433.                 ("Peter Norvig", 2),
    
  1434.                 ("Stuart Russell", 0),
    
  1435.                 ("Wesley J. Chun", 0),
    
  1436.             ],
    
  1437.         )
    
  1438. 
    
  1439.     @skipUnlessAnyDBFeature("allows_group_by_pk", "allows_group_by_selected_pks")
    
  1440.     def test_aggregate_duplicate_columns_only(self):
    
  1441.         # Works with only() too.
    
  1442.         results = Author.objects.only("id", "name").annotate(
    
  1443.             num_contacts=Count("book_contact_set")
    
  1444.         )
    
  1445.         _, _, grouping = results.query.get_compiler(using="default").pre_sql_setup()
    
  1446.         self.assertEqual(len(grouping), 1)
    
  1447.         self.assertIn("id", grouping[0][0])
    
  1448.         self.assertNotIn("name", grouping[0][0])
    
  1449.         self.assertNotIn("age", grouping[0][0])
    
  1450.         self.assertEqual(
    
  1451.             [(a.name, a.num_contacts) for a in results.order_by("name")],
    
  1452.             [
    
  1453.                 ("Adrian Holovaty", 1),
    
  1454.                 ("Brad Dayley", 1),
    
  1455.                 ("Jacob Kaplan-Moss", 0),
    
  1456.                 ("James Bennett", 1),
    
  1457.                 ("Jeffrey Forcier", 1),
    
  1458.                 ("Paul Bissex", 0),
    
  1459.                 ("Peter Norvig", 2),
    
  1460.                 ("Stuart Russell", 0),
    
  1461.                 ("Wesley J. Chun", 0),
    
  1462.             ],
    
  1463.         )
    
  1464. 
    
  1465.     @skipUnlessAnyDBFeature("allows_group_by_pk", "allows_group_by_selected_pks")
    
  1466.     def test_aggregate_duplicate_columns_select_related(self):
    
  1467.         # And select_related()
    
  1468.         results = Book.objects.select_related("contact").annotate(
    
  1469.             num_authors=Count("authors")
    
  1470.         )
    
  1471.         _, _, grouping = results.query.get_compiler(using="default").pre_sql_setup()
    
  1472.         # In the case of `group_by_selected_pks` we also group by contact.id
    
  1473.         # because of the select_related.
    
  1474.         self.assertEqual(
    
  1475.             len(grouping), 1 if connection.features.allows_group_by_pk else 2
    
  1476.         )
    
  1477.         self.assertIn("id", grouping[0][0])
    
  1478.         self.assertNotIn("name", grouping[0][0])
    
  1479.         self.assertNotIn("contact", grouping[0][0])
    
  1480.         self.assertEqual(
    
  1481.             [(b.name, b.num_authors) for b in results.order_by("name")],
    
  1482.             [
    
  1483.                 ("Artificial Intelligence: A Modern Approach", 2),
    
  1484.                 (
    
  1485.                     "Paradigms of Artificial Intelligence Programming: Case Studies in "
    
  1486.                     "Common Lisp",
    
  1487.                     1,
    
  1488.                 ),
    
  1489.                 ("Practical Django Projects", 1),
    
  1490.                 ("Python Web Development with Django", 3),
    
  1491.                 ("Sams Teach Yourself Django in 24 Hours", 1),
    
  1492.                 ("The Definitive Guide to Django: Web Development Done Right", 2),
    
  1493.             ],
    
  1494.         )
    
  1495. 
    
  1496.     @skipUnlessDBFeature("allows_group_by_selected_pks")
    
  1497.     def test_aggregate_unmanaged_model_columns(self):
    
  1498.         """
    
  1499.         Unmanaged models are sometimes used to represent database views which
    
  1500.         may not allow grouping by selected primary key.
    
  1501.         """
    
  1502. 
    
  1503.         def assertQuerysetResults(queryset):
    
  1504.             self.assertEqual(
    
  1505.                 [(b.name, b.num_authors) for b in queryset.order_by("name")],
    
  1506.                 [
    
  1507.                     ("Artificial Intelligence: A Modern Approach", 2),
    
  1508.                     (
    
  1509.                         "Paradigms of Artificial Intelligence Programming: Case "
    
  1510.                         "Studies in Common Lisp",
    
  1511.                         1,
    
  1512.                     ),
    
  1513.                     ("Practical Django Projects", 1),
    
  1514.                     ("Python Web Development with Django", 3),
    
  1515.                     ("Sams Teach Yourself Django in 24 Hours", 1),
    
  1516.                     ("The Definitive Guide to Django: Web Development Done Right", 2),
    
  1517.                 ],
    
  1518.             )
    
  1519. 
    
  1520.         queryset = Book.objects.select_related("contact").annotate(
    
  1521.             num_authors=Count("authors")
    
  1522.         )
    
  1523.         # Unmanaged origin model.
    
  1524.         with mock.patch.object(Book._meta, "managed", False):
    
  1525.             _, _, grouping = queryset.query.get_compiler(
    
  1526.                 using="default"
    
  1527.             ).pre_sql_setup()
    
  1528.             self.assertEqual(len(grouping), len(Book._meta.fields) + 1)
    
  1529.             for index, field in enumerate(Book._meta.fields):
    
  1530.                 self.assertIn(field.name, grouping[index][0])
    
  1531.             self.assertIn(Author._meta.pk.name, grouping[-1][0])
    
  1532.             assertQuerysetResults(queryset)
    
  1533.         # Unmanaged related model.
    
  1534.         with mock.patch.object(Author._meta, "managed", False):
    
  1535.             _, _, grouping = queryset.query.get_compiler(
    
  1536.                 using="default"
    
  1537.             ).pre_sql_setup()
    
  1538.             self.assertEqual(len(grouping), len(Author._meta.fields) + 1)
    
  1539.             self.assertIn(Book._meta.pk.name, grouping[0][0])
    
  1540.             for index, field in enumerate(Author._meta.fields):
    
  1541.                 self.assertIn(field.name, grouping[index + 1][0])
    
  1542.             assertQuerysetResults(queryset)
    
  1543. 
    
  1544.     @skipUnlessDBFeature("allows_group_by_selected_pks")
    
  1545.     def test_aggregate_unmanaged_model_as_tables(self):
    
  1546.         qs = Book.objects.select_related("contact").annotate(
    
  1547.             num_authors=Count("authors")
    
  1548.         )
    
  1549.         # Force treating unmanaged models as tables.
    
  1550.         with mock.patch(
    
  1551.             "django.db.connection.features.allows_group_by_selected_pks_on_model",
    
  1552.             return_value=True,
    
  1553.         ):
    
  1554.             with mock.patch.object(Book._meta, "managed", False), mock.patch.object(
    
  1555.                 Author._meta, "managed", False
    
  1556.             ):
    
  1557.                 _, _, grouping = qs.query.get_compiler(using="default").pre_sql_setup()
    
  1558.                 self.assertEqual(len(grouping), 2)
    
  1559.                 self.assertIn("id", grouping[0][0])
    
  1560.                 self.assertIn("id", grouping[1][0])
    
  1561.                 self.assertQuerysetEqual(
    
  1562.                     qs.order_by("name"),
    
  1563.                     [
    
  1564.                         ("Artificial Intelligence: A Modern Approach", 2),
    
  1565.                         (
    
  1566.                             "Paradigms of Artificial Intelligence Programming: Case "
    
  1567.                             "Studies in Common Lisp",
    
  1568.                             1,
    
  1569.                         ),
    
  1570.                         ("Practical Django Projects", 1),
    
  1571.                         ("Python Web Development with Django", 3),
    
  1572.                         ("Sams Teach Yourself Django in 24 Hours", 1),
    
  1573.                         (
    
  1574.                             "The Definitive Guide to Django: Web Development Done "
    
  1575.                             "Right",
    
  1576.                             2,
    
  1577.                         ),
    
  1578.                     ],
    
  1579.                     attrgetter("name", "num_authors"),
    
  1580.                 )
    
  1581. 
    
  1582.     def test_reverse_join_trimming(self):
    
  1583.         qs = Author.objects.annotate(Count("book_contact_set__contact"))
    
  1584.         self.assertIn(" JOIN ", str(qs.query))
    
  1585. 
    
  1586.     def test_aggregation_with_generic_reverse_relation(self):
    
  1587.         """
    
  1588.         Regression test for #10870:  Aggregates with joins ignore extra
    
  1589.         filters provided by setup_joins
    
  1590. 
    
  1591.         tests aggregations with generic reverse relations
    
  1592.         """
    
  1593.         django_book = Book.objects.get(name="Practical Django Projects")
    
  1594.         ItemTag.objects.create(
    
  1595.             object_id=django_book.id,
    
  1596.             tag="intermediate",
    
  1597.             content_type=ContentType.objects.get_for_model(django_book),
    
  1598.         )
    
  1599.         ItemTag.objects.create(
    
  1600.             object_id=django_book.id,
    
  1601.             tag="django",
    
  1602.             content_type=ContentType.objects.get_for_model(django_book),
    
  1603.         )
    
  1604.         # Assign a tag to model with same PK as the book above. If the JOIN
    
  1605.         # used in aggregation doesn't have content type as part of the
    
  1606.         # condition the annotation will also count the 'hi mom' tag for b.
    
  1607.         wmpk = WithManualPK.objects.create(id=django_book.pk)
    
  1608.         ItemTag.objects.create(
    
  1609.             object_id=wmpk.id,
    
  1610.             tag="hi mom",
    
  1611.             content_type=ContentType.objects.get_for_model(wmpk),
    
  1612.         )
    
  1613.         ai_book = Book.objects.get(
    
  1614.             name__startswith="Paradigms of Artificial Intelligence"
    
  1615.         )
    
  1616.         ItemTag.objects.create(
    
  1617.             object_id=ai_book.id,
    
  1618.             tag="intermediate",
    
  1619.             content_type=ContentType.objects.get_for_model(ai_book),
    
  1620.         )
    
  1621. 
    
  1622.         self.assertEqual(Book.objects.aggregate(Count("tags")), {"tags__count": 3})
    
  1623.         results = Book.objects.annotate(Count("tags")).order_by("-tags__count", "name")
    
  1624.         self.assertEqual(
    
  1625.             [(b.name, b.tags__count) for b in results],
    
  1626.             [
    
  1627.                 ("Practical Django Projects", 2),
    
  1628.                 (
    
  1629.                     "Paradigms of Artificial Intelligence Programming: Case Studies in "
    
  1630.                     "Common Lisp",
    
  1631.                     1,
    
  1632.                 ),
    
  1633.                 ("Artificial Intelligence: A Modern Approach", 0),
    
  1634.                 ("Python Web Development with Django", 0),
    
  1635.                 ("Sams Teach Yourself Django in 24 Hours", 0),
    
  1636.                 ("The Definitive Guide to Django: Web Development Done Right", 0),
    
  1637.             ],
    
  1638.         )
    
  1639. 
    
  1640.     def test_negated_aggregation(self):
    
  1641.         expected_results = Author.objects.exclude(
    
  1642.             pk__in=Author.objects.annotate(book_cnt=Count("book")).filter(book_cnt=2)
    
  1643.         ).order_by("name")
    
  1644.         expected_results = [a.name for a in expected_results]
    
  1645.         qs = (
    
  1646.             Author.objects.annotate(book_cnt=Count("book"))
    
  1647.             .exclude(Q(book_cnt=2), Q(book_cnt=2))
    
  1648.             .order_by("name")
    
  1649.         )
    
  1650.         self.assertQuerysetEqual(qs, expected_results, lambda b: b.name)
    
  1651.         expected_results = Author.objects.exclude(
    
  1652.             pk__in=Author.objects.annotate(book_cnt=Count("book")).filter(book_cnt=2)
    
  1653.         ).order_by("name")
    
  1654.         expected_results = [a.name for a in expected_results]
    
  1655.         qs = (
    
  1656.             Author.objects.annotate(book_cnt=Count("book"))
    
  1657.             .exclude(Q(book_cnt=2) | Q(book_cnt=2))
    
  1658.             .order_by("name")
    
  1659.         )
    
  1660.         self.assertQuerysetEqual(qs, expected_results, lambda b: b.name)
    
  1661. 
    
  1662.     def test_name_filters(self):
    
  1663.         qs = (
    
  1664.             Author.objects.annotate(Count("book"))
    
  1665.             .filter(Q(book__count__exact=2) | Q(name="Adrian Holovaty"))
    
  1666.             .order_by("name")
    
  1667.         )
    
  1668.         self.assertQuerysetEqual(
    
  1669.             qs, ["Adrian Holovaty", "Peter Norvig"], lambda b: b.name
    
  1670.         )
    
  1671. 
    
  1672.     def test_name_expressions(self):
    
  1673.         # Aggregates are spotted correctly from F objects.
    
  1674.         # Note that Adrian's age is 34 in the fixtures, and he has one book
    
  1675.         # so both conditions match one author.
    
  1676.         qs = (
    
  1677.             Author.objects.annotate(Count("book"))
    
  1678.             .filter(Q(name="Peter Norvig") | Q(age=F("book__count") + 33))
    
  1679.             .order_by("name")
    
  1680.         )
    
  1681.         self.assertQuerysetEqual(
    
  1682.             qs, ["Adrian Holovaty", "Peter Norvig"], lambda b: b.name
    
  1683.         )
    
  1684. 
    
  1685.     def test_filter_aggregates_or_connector(self):
    
  1686.         q1 = Q(price__gt=50)
    
  1687.         q2 = Q(authors__count__gt=1)
    
  1688.         query = Book.objects.annotate(Count("authors")).filter(q1 | q2).order_by("pk")
    
  1689.         self.assertQuerysetEqual(
    
  1690.             query,
    
  1691.             [self.b1.pk, self.b4.pk, self.b5.pk, self.b6.pk],
    
  1692.             attrgetter("pk"),
    
  1693.         )
    
  1694. 
    
  1695.     def test_filter_aggregates_negated_and_connector(self):
    
  1696.         q1 = Q(price__gt=50)
    
  1697.         q2 = Q(authors__count__gt=1)
    
  1698.         query = (
    
  1699.             Book.objects.annotate(Count("authors")).filter(~(q1 & q2)).order_by("pk")
    
  1700.         )
    
  1701.         self.assertQuerysetEqual(
    
  1702.             query,
    
  1703.             [self.b1.pk, self.b2.pk, self.b3.pk, self.b4.pk, self.b6.pk],
    
  1704.             attrgetter("pk"),
    
  1705.         )
    
  1706. 
    
  1707.     def test_filter_aggregates_xor_connector(self):
    
  1708.         q1 = Q(price__gt=50)
    
  1709.         q2 = Q(authors__count__gt=1)
    
  1710.         query = Book.objects.annotate(Count("authors")).filter(q1 ^ q2).order_by("pk")
    
  1711.         self.assertQuerysetEqual(
    
  1712.             query,
    
  1713.             [self.b1.pk, self.b4.pk, self.b6.pk],
    
  1714.             attrgetter("pk"),
    
  1715.         )
    
  1716. 
    
  1717.     def test_filter_aggregates_negated_xor_connector(self):
    
  1718.         q1 = Q(price__gt=50)
    
  1719.         q2 = Q(authors__count__gt=1)
    
  1720.         query = (
    
  1721.             Book.objects.annotate(Count("authors")).filter(~(q1 ^ q2)).order_by("pk")
    
  1722.         )
    
  1723.         self.assertQuerysetEqual(
    
  1724.             query,
    
  1725.             [self.b2.pk, self.b3.pk, self.b5.pk],
    
  1726.             attrgetter("pk"),
    
  1727.         )
    
  1728. 
    
  1729.     def test_ticket_11293_q_immutable(self):
    
  1730.         """
    
  1731.         Splitting a q object to parts for where/having doesn't alter
    
  1732.         the original q-object.
    
  1733.         """
    
  1734.         q1 = Q(isbn="")
    
  1735.         q2 = Q(authors__count__gt=1)
    
  1736.         query = Book.objects.annotate(Count("authors"))
    
  1737.         query.filter(q1 | q2)
    
  1738.         self.assertEqual(len(q2.children), 1)
    
  1739. 
    
  1740.     def test_fobj_group_by(self):
    
  1741.         """
    
  1742.         An F() object referring to related column works correctly in group by.
    
  1743.         """
    
  1744.         qs = Book.objects.annotate(account=Count("authors")).filter(
    
  1745.             account=F("publisher__num_awards")
    
  1746.         )
    
  1747.         self.assertQuerysetEqual(
    
  1748.             qs, ["Sams Teach Yourself Django in 24 Hours"], lambda b: b.name
    
  1749.         )
    
  1750. 
    
  1751.     def test_annotate_reserved_word(self):
    
  1752.         """
    
  1753.         Regression #18333 - Ensure annotated column name is properly quoted.
    
  1754.         """
    
  1755.         vals = Book.objects.annotate(select=Count("authors__id")).aggregate(
    
  1756.             Sum("select"), Avg("select")
    
  1757.         )
    
  1758.         self.assertEqual(
    
  1759.             vals,
    
  1760.             {
    
  1761.                 "select__sum": 10,
    
  1762.                 "select__avg": Approximate(1.666, places=2),
    
  1763.             },
    
  1764.         )
    
  1765. 
    
  1766.     def test_annotate_on_relation(self):
    
  1767.         book = Book.objects.annotate(
    
  1768.             avg_price=Avg("price"), publisher_name=F("publisher__name")
    
  1769.         ).get(pk=self.b1.pk)
    
  1770.         self.assertEqual(book.avg_price, 30.00)
    
  1771.         self.assertEqual(book.publisher_name, "Apress")
    
  1772. 
    
  1773.     def test_aggregate_on_relation(self):
    
  1774.         # A query with an existing annotation aggregation on a relation should
    
  1775.         # succeed.
    
  1776.         qs = Book.objects.annotate(avg_price=Avg("price")).aggregate(
    
  1777.             publisher_awards=Sum("publisher__num_awards")
    
  1778.         )
    
  1779.         self.assertEqual(qs["publisher_awards"], 30)
    
  1780. 
    
  1781.     def test_annotate_distinct_aggregate(self):
    
  1782.         # There are three books with rating of 4.0 and two of the books have
    
  1783.         # the same price. Hence, the distinct removes one rating of 4.0
    
  1784.         # from the results.
    
  1785.         vals1 = (
    
  1786.             Book.objects.values("rating", "price")
    
  1787.             .distinct()
    
  1788.             .aggregate(result=Sum("rating"))
    
  1789.         )
    
  1790.         vals2 = Book.objects.aggregate(result=Sum("rating") - Value(4.0))
    
  1791.         self.assertEqual(vals1, vals2)
    
  1792. 
    
  1793.     def test_annotate_values_list_flat(self):
    
  1794.         """Find ages that are shared by at least two authors."""
    
  1795.         qs = (
    
  1796.             Author.objects.values_list("age", flat=True)
    
  1797.             .annotate(age_count=Count("age"))
    
  1798.             .filter(age_count__gt=1)
    
  1799.         )
    
  1800.         self.assertSequenceEqual(qs, [29])
    
  1801. 
    
  1802.     def test_allow_distinct(self):
    
  1803.         class MyAggregate(Aggregate):
    
  1804.             pass
    
  1805. 
    
  1806.         with self.assertRaisesMessage(TypeError, "MyAggregate does not allow distinct"):
    
  1807.             MyAggregate("foo", distinct=True)
    
  1808. 
    
  1809.         class DistinctAggregate(Aggregate):
    
  1810.             allow_distinct = True
    
  1811. 
    
  1812.         DistinctAggregate("foo", distinct=True)
    
  1813. 
    
  1814.     @skipUnlessDBFeature("supports_subqueries_in_group_by")
    
  1815.     def test_having_subquery_select(self):
    
  1816.         authors = Author.objects.filter(pk=self.a1.pk)
    
  1817.         books = Book.objects.annotate(Count("authors")).filter(
    
  1818.             Q(authors__in=authors) | Q(authors__count__gt=2)
    
  1819.         )
    
  1820.         self.assertEqual(set(books), {self.b1, self.b4})
    
  1821. 
    
  1822. 
    
  1823. class JoinPromotionTests(TestCase):
    
  1824.     def test_ticket_21150(self):
    
  1825.         b = Bravo.objects.create()
    
  1826.         c = Charlie.objects.create(bravo=b)
    
  1827.         qs = Charlie.objects.select_related("alfa").annotate(Count("bravo__charlie"))
    
  1828.         self.assertSequenceEqual(qs, [c])
    
  1829.         self.assertIs(qs[0].alfa, None)
    
  1830.         a = Alfa.objects.create()
    
  1831.         c.alfa = a
    
  1832.         c.save()
    
  1833.         # Force re-evaluation
    
  1834.         qs = qs.all()
    
  1835.         self.assertSequenceEqual(qs, [c])
    
  1836.         self.assertEqual(qs[0].alfa, a)
    
  1837. 
    
  1838.     def test_existing_join_not_promoted(self):
    
  1839.         # No promotion for existing joins
    
  1840.         qs = Charlie.objects.filter(alfa__name__isnull=False).annotate(
    
  1841.             Count("alfa__name")
    
  1842.         )
    
  1843.         self.assertIn(" INNER JOIN ", str(qs.query))
    
  1844.         # Also, the existing join is unpromoted when doing filtering for already
    
  1845.         # promoted join.
    
  1846.         qs = Charlie.objects.annotate(Count("alfa__name")).filter(
    
  1847.             alfa__name__isnull=False
    
  1848.         )
    
  1849.         self.assertIn(" INNER JOIN ", str(qs.query))
    
  1850.         # But, as the join is nullable first use by annotate will be LOUTER
    
  1851.         qs = Charlie.objects.annotate(Count("alfa__name"))
    
  1852.         self.assertIn(" LEFT OUTER JOIN ", str(qs.query))
    
  1853. 
    
  1854.     def test_non_nullable_fk_not_promoted(self):
    
  1855.         qs = Book.objects.annotate(Count("contact__name"))
    
  1856.         self.assertIn(" INNER JOIN ", str(qs.query))
    
  1857. 
    
  1858. 
    
  1859. class SelfReferentialFKTests(TestCase):
    
  1860.     def test_ticket_24748(self):
    
  1861.         t1 = SelfRefFK.objects.create(name="t1")
    
  1862.         SelfRefFK.objects.create(name="t2", parent=t1)
    
  1863.         SelfRefFK.objects.create(name="t3", parent=t1)
    
  1864.         self.assertQuerysetEqual(
    
  1865.             SelfRefFK.objects.annotate(num_children=Count("children")).order_by("name"),
    
  1866.             [("t1", 2), ("t2", 0), ("t3", 0)],
    
  1867.             lambda x: (x.name, x.num_children),
    
  1868.         )