aggregation.txt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. ===========
  2. Aggregation
  3. ===========
  4. .. currentmodule:: django.db.models
  5. The topic guide on :doc:`Django's database-abstraction API </topics/db/queries>`
  6. described the way that you can use Django queries that create,
  7. retrieve, update and delete individual objects. However, sometimes you will
  8. need to retrieve values that are derived by summarizing or *aggregating* a
  9. collection of objects. This topic guide describes the ways that aggregate values
  10. can be generated and returned using Django queries.
  11. Throughout this guide, we'll refer to the following models. These models are
  12. used to track the inventory for a series of online bookstores:
  13. .. _queryset-model-example:
  14. .. code-block:: python
  15. from django.db import models
  16. class Author(models.Model):
  17. name = models.CharField(max_length=100)
  18. age = models.IntegerField()
  19. class Publisher(models.Model):
  20. name = models.CharField(max_length=300)
  21. class Book(models.Model):
  22. name = models.CharField(max_length=300)
  23. pages = models.IntegerField()
  24. price = models.DecimalField(max_digits=10, decimal_places=2)
  25. rating = models.FloatField()
  26. authors = models.ManyToManyField(Author)
  27. publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
  28. pubdate = models.DateField()
  29. class Store(models.Model):
  30. name = models.CharField(max_length=300)
  31. books = models.ManyToManyField(Book)
  32. Cheat sheet
  33. ===========
  34. In a hurry? Here's how to do common aggregate queries, assuming the models
  35. above:
  36. .. code-block:: pycon
  37. # Total number of books.
  38. >>> Book.objects.count()
  39. 2452
  40. # Total number of books with publisher=BaloneyPress
  41. >>> Book.objects.filter(publisher__name="BaloneyPress").count()
  42. 73
  43. # Average price across all books, provide default to be returned instead
  44. # of None if no books exist.
  45. >>> from django.db.models import Avg
  46. >>> Book.objects.aggregate(Avg("price", default=0))
  47. {'price__avg': 34.35}
  48. # Max price across all books, provide default to be returned instead of
  49. # None if no books exist.
  50. >>> from django.db.models import Max
  51. >>> Book.objects.aggregate(Max("price", default=0))
  52. {'price__max': Decimal('81.20')}
  53. # Difference between the highest priced book and the average price of all books.
  54. >>> from django.db.models import FloatField
  55. >>> Book.objects.aggregate(
  56. ... price_diff=Max("price", output_field=FloatField()) - Avg("price")
  57. ... )
  58. {'price_diff': 46.85}
  59. # All the following queries involve traversing the Book<->Publisher
  60. # foreign key relationship backwards.
  61. # Each publisher, each with a count of books as a "num_books" attribute.
  62. >>> from django.db.models import Count
  63. >>> pubs = Publisher.objects.annotate(num_books=Count("book"))
  64. >>> pubs
  65. <QuerySet [<Publisher: BaloneyPress>, <Publisher: SalamiPress>, ...]>
  66. >>> pubs[0].num_books
  67. 73
  68. # Each publisher, with a separate count of books with a rating above and below 5
  69. >>> from django.db.models import Q
  70. >>> above_5 = Count("book", filter=Q(book__rating__gt=5))
  71. >>> below_5 = Count("book", filter=Q(book__rating__lte=5))
  72. >>> pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)
  73. >>> pubs[0].above_5
  74. 23
  75. >>> pubs[0].below_5
  76. 12
  77. # The top 5 publishers, in order by number of books.
  78. >>> pubs = Publisher.objects.annotate(num_books=Count("book")).order_by("-num_books")[:5]
  79. >>> pubs[0].num_books
  80. 1323
  81. Generating aggregates over a ``QuerySet``
  82. =========================================
  83. Django provides two ways to generate aggregates. The first way is to generate
  84. summary values over an entire ``QuerySet``. For example, say you wanted to
  85. calculate the average price of all books available for sale. Django's query
  86. syntax provides a means for describing the set of all books:
  87. .. code-block:: pycon
  88. >>> Book.objects.all()
  89. What we need is a way to calculate summary values over the objects that
  90. belong to this ``QuerySet``. This is done by appending an ``aggregate()``
  91. clause onto the ``QuerySet``:
  92. .. code-block:: pycon
  93. >>> from django.db.models import Avg
  94. >>> Book.objects.all().aggregate(Avg("price"))
  95. {'price__avg': 34.35}
  96. The ``all()`` is redundant in this example, so this could be simplified to:
  97. .. code-block:: pycon
  98. >>> Book.objects.aggregate(Avg("price"))
  99. {'price__avg': 34.35}
  100. The argument to the ``aggregate()`` clause describes the aggregate value that
  101. we want to compute - in this case, the average of the ``price`` field on the
  102. ``Book`` model. A list of the aggregate functions that are available can be
  103. found in the :ref:`QuerySet reference <aggregation-functions>`.
  104. ``aggregate()`` is a terminal clause for a ``QuerySet`` that, when invoked,
  105. returns a dictionary of name-value pairs. The name is an identifier for the
  106. aggregate value; the value is the computed aggregate. The name is
  107. automatically generated from the name of the field and the aggregate function.
  108. If you want to manually specify a name for the aggregate value, you can do so
  109. by providing that name when you specify the aggregate clause:
  110. .. code-block:: pycon
  111. >>> Book.objects.aggregate(average_price=Avg("price"))
  112. {'average_price': 34.35}
  113. If you want to generate more than one aggregate, you add another argument to
  114. the ``aggregate()`` clause. So, if we also wanted to know the maximum and
  115. minimum price of all books, we would issue the query:
  116. .. code-block:: pycon
  117. >>> from django.db.models import Avg, Max, Min
  118. >>> Book.objects.aggregate(Avg("price"), Max("price"), Min("price"))
  119. {'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}
  120. Generating aggregates for each item in a ``QuerySet``
  121. =====================================================
  122. The second way to generate summary values is to generate an independent
  123. summary for each object in a :class:`.QuerySet`. For example, if you are
  124. retrieving a list of books, you may want to know how many authors contributed
  125. to each book. Each Book has a many-to-many relationship with the Author; we
  126. want to summarize this relationship for each book in the ``QuerySet``.
  127. Per-object summaries can be generated using the
  128. :meth:`~.QuerySet.annotate` clause. When an ``annotate()`` clause is
  129. specified, each object in the ``QuerySet`` will be annotated with the
  130. specified values.
  131. The syntax for these annotations is identical to that used for the
  132. :meth:`~.QuerySet.aggregate` clause. Each argument to ``annotate()`` describes
  133. an aggregate that is to be calculated. For example, to annotate books with the
  134. number of authors:
  135. .. code-block:: pycon
  136. # Build an annotated queryset
  137. >>> from django.db.models import Count
  138. >>> q = Book.objects.annotate(Count("authors"))
  139. # Interrogate the first object in the queryset
  140. >>> q[0]
  141. <Book: The Definitive Guide to Django>
  142. >>> q[0].authors__count
  143. 2
  144. # Interrogate the second object in the queryset
  145. >>> q[1]
  146. <Book: Practical Django Projects>
  147. >>> q[1].authors__count
  148. 1
  149. As with ``aggregate()``, the name for the annotation is automatically derived
  150. from the name of the aggregate function and the name of the field being
  151. aggregated. You can override this default name by providing an alias when you
  152. specify the annotation:
  153. .. code-block:: pycon
  154. >>> q = Book.objects.annotate(num_authors=Count("authors"))
  155. >>> q[0].num_authors
  156. 2
  157. >>> q[1].num_authors
  158. 1
  159. Unlike ``aggregate()``, ``annotate()`` is *not* a terminal clause. The output
  160. of the ``annotate()`` clause is a ``QuerySet``; this ``QuerySet`` can be
  161. modified using any other ``QuerySet`` operation, including ``filter()``,
  162. ``order_by()``, or even additional calls to ``annotate()``.
  163. .. _combining-multiple-aggregations:
  164. Combining multiple aggregations
  165. -------------------------------
  166. Combining multiple aggregations with ``annotate()`` will :ticket:`yield the
  167. wrong results <10060>` because joins are used instead of subqueries:
  168. .. code-block:: pycon
  169. >>> book = Book.objects.first()
  170. >>> book.authors.count()
  171. 2
  172. >>> book.store_set.count()
  173. 3
  174. >>> q = Book.objects.annotate(Count("authors"), Count("store"))
  175. >>> q[0].authors__count
  176. 6
  177. >>> q[0].store__count
  178. 6
  179. For most aggregates, there is no way to avoid this problem, however, the
  180. :class:`~django.db.models.Count` aggregate has a ``distinct`` parameter that
  181. may help:
  182. .. code-block:: pycon
  183. >>> q = Book.objects.annotate(
  184. ... Count("authors", distinct=True), Count("store", distinct=True)
  185. ... )
  186. >>> q[0].authors__count
  187. 2
  188. >>> q[0].store__count
  189. 3
  190. .. admonition:: If in doubt, inspect the SQL query!
  191. In order to understand what happens in your query, consider inspecting the
  192. ``query`` property of your ``QuerySet``.
  193. Joins and aggregates
  194. ====================
  195. So far, we have dealt with aggregates over fields that belong to the
  196. model being queried. However, sometimes the value you want to aggregate
  197. will belong to a model that is related to the model you are querying.
  198. When specifying the field to be aggregated in an aggregate function, Django
  199. will allow you to use the same :ref:`double underscore notation
  200. <field-lookups-intro>` that is used when referring to related fields in
  201. filters. Django will then handle any table joins that are required to retrieve
  202. and aggregate the related value.
  203. For example, to find the price range of books offered in each store,
  204. you could use the annotation:
  205. .. code-block:: pycon
  206. >>> from django.db.models import Max, Min
  207. >>> Store.objects.annotate(min_price=Min("books__price"), max_price=Max("books__price"))
  208. This tells Django to retrieve the ``Store`` model, join (through the
  209. many-to-many relationship) with the ``Book`` model, and aggregate on the
  210. price field of the book model to produce a minimum and maximum value.
  211. The same rules apply to the ``aggregate()`` clause. If you wanted to
  212. know the lowest and highest price of any book that is available for sale
  213. in any of the stores, you could use the aggregate:
  214. .. code-block:: pycon
  215. >>> Store.objects.aggregate(min_price=Min("books__price"), max_price=Max("books__price"))
  216. Join chains can be as deep as you require. For example, to extract the
  217. age of the youngest author of any book available for sale, you could
  218. issue the query:
  219. .. code-block:: pycon
  220. >>> Store.objects.aggregate(youngest_age=Min("books__authors__age"))
  221. Following relationships backwards
  222. ---------------------------------
  223. In a way similar to :ref:`lookups-that-span-relationships`, aggregations and
  224. annotations on fields of models or models that are related to the one you are
  225. querying can include traversing "reverse" relationships. The lowercase name
  226. of related models and double-underscores are used here too.
  227. For example, we can ask for all publishers, annotated with their respective
  228. total book stock counters (note how we use ``'book'`` to specify the
  229. ``Publisher`` -> ``Book`` reverse foreign key hop):
  230. .. code-block:: pycon
  231. >>> from django.db.models import Avg, Count, Min, Sum
  232. >>> Publisher.objects.annotate(Count("book"))
  233. (Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute
  234. called ``book__count``.)
  235. We can also ask for the oldest book of any of those managed by every publisher:
  236. .. code-block:: pycon
  237. >>> Publisher.objects.aggregate(oldest_pubdate=Min("book__pubdate"))
  238. (The resulting dictionary will have a key called ``'oldest_pubdate'``. If no
  239. such alias were specified, it would be the rather long ``'book__pubdate__min'``.)
  240. This doesn't apply just to foreign keys. It also works with many-to-many
  241. relations. For example, we can ask for every author, annotated with the total
  242. number of pages considering all the books the author has (co-)authored (note how we
  243. use ``'book'`` to specify the ``Author`` -> ``Book`` reverse many-to-many hop):
  244. .. code-block:: pycon
  245. >>> Author.objects.annotate(total_pages=Sum("book__pages"))
  246. (Every ``Author`` in the resulting ``QuerySet`` will have an extra attribute
  247. called ``total_pages``. If no such alias were specified, it would be the rather
  248. long ``book__pages__sum``.)
  249. Or ask for the average rating of all the books written by author(s) we have on
  250. file:
  251. .. code-block:: pycon
  252. >>> Author.objects.aggregate(average_rating=Avg("book__rating"))
  253. (The resulting dictionary will have a key called ``'average_rating'``. If no
  254. such alias were specified, it would be the rather long ``'book__rating__avg'``.)
  255. Aggregations and other ``QuerySet`` clauses
  256. ===========================================
  257. ``filter()`` and ``exclude()``
  258. ------------------------------
  259. Aggregates can also participate in filters. Any ``filter()`` (or
  260. ``exclude()``) applied to normal model fields will have the effect of
  261. constraining the objects that are considered for aggregation.
  262. When used with an ``annotate()`` clause, a filter has the effect of
  263. constraining the objects for which an annotation is calculated. For example,
  264. you can generate an annotated list of all books that have a title starting
  265. with "Django" using the query:
  266. .. code-block:: pycon
  267. >>> from django.db.models import Avg, Count
  268. >>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count("authors"))
  269. When used with an ``aggregate()`` clause, a filter has the effect of
  270. constraining the objects over which the aggregate is calculated.
  271. For example, you can generate the average price of all books with a
  272. title that starts with "Django" using the query:
  273. .. code-block:: pycon
  274. >>> Book.objects.filter(name__startswith="Django").aggregate(Avg("price"))
  275. .. _filtering-on-annotations:
  276. Filtering on annotations
  277. ~~~~~~~~~~~~~~~~~~~~~~~~
  278. Annotated values can also be filtered. The alias for the annotation can be
  279. used in ``filter()`` and ``exclude()`` clauses in the same way as any other
  280. model field.
  281. For example, to generate a list of books that have more than one author,
  282. you can issue the query:
  283. .. code-block:: pycon
  284. >>> Book.objects.annotate(num_authors=Count("authors")).filter(num_authors__gt=1)
  285. This query generates an annotated result set, and then generates a filter
  286. based upon that annotation.
  287. If you need two annotations with two separate filters you can use the
  288. ``filter`` argument with any aggregate. For example, to generate a list of
  289. authors with a count of highly rated books:
  290. .. code-block:: pycon
  291. >>> highly_rated = Count("book", filter=Q(book__rating__gte=7))
  292. >>> Author.objects.annotate(num_books=Count("book"), highly_rated_books=highly_rated)
  293. Each ``Author`` in the result set will have the ``num_books`` and
  294. ``highly_rated_books`` attributes. See also :ref:`conditional-aggregation`.
  295. .. admonition:: Choosing between ``filter`` and ``QuerySet.filter()``
  296. Avoid using the ``filter`` argument with a single annotation or
  297. aggregation. It's more efficient to use ``QuerySet.filter()`` to exclude
  298. rows. The aggregation ``filter`` argument is only useful when using two or
  299. more aggregations over the same relations with different conditionals.
  300. Order of ``annotate()`` and ``filter()`` clauses
  301. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  302. When developing a complex query that involves both ``annotate()`` and
  303. ``filter()`` clauses, pay particular attention to the order in which the
  304. clauses are applied to the ``QuerySet``.
  305. When an ``annotate()`` clause is applied to a query, the annotation is computed
  306. over the state of the query up to the point where the annotation is requested.
  307. The practical implication of this is that ``filter()`` and ``annotate()`` are
  308. not commutative operations.
  309. Given:
  310. * Publisher A has two books with ratings 4 and 5.
  311. * Publisher B has two books with ratings 1 and 4.
  312. * Publisher C has one book with rating 1.
  313. Here's an example with the ``Count`` aggregate:
  314. .. code-block:: pycon
  315. >>> a, b = Publisher.objects.annotate(num_books=Count("book", distinct=True)).filter(
  316. ... book__rating__gt=3.0
  317. ... )
  318. >>> a, a.num_books
  319. (<Publisher: A>, 2)
  320. >>> b, b.num_books
  321. (<Publisher: B>, 2)
  322. >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count("book"))
  323. >>> a, a.num_books
  324. (<Publisher: A>, 2)
  325. >>> b, b.num_books
  326. (<Publisher: B>, 1)
  327. Both queries return a list of publishers that have at least one book with a
  328. rating exceeding 3.0, hence publisher C is excluded.
  329. In the first query, the annotation precedes the filter, so the filter has no
  330. effect on the annotation. ``distinct=True`` is required to avoid a :ref:`query
  331. bug <combining-multiple-aggregations>`.
  332. The second query counts the number of books that have a rating exceeding 3.0
  333. for each publisher. The filter precedes the annotation, so the filter
  334. constrains the objects considered when calculating the annotation.
  335. Here's another example with the ``Avg`` aggregate:
  336. .. code-block:: pycon
  337. >>> a, b = Publisher.objects.annotate(avg_rating=Avg("book__rating")).filter(
  338. ... book__rating__gt=3.0
  339. ... )
  340. >>> a, a.avg_rating
  341. (<Publisher: A>, 4.5) # (5+4)/2
  342. >>> b, b.avg_rating
  343. (<Publisher: B>, 2.5) # (1+4)/2
  344. >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(
  345. ... avg_rating=Avg("book__rating")
  346. ... )
  347. >>> a, a.avg_rating
  348. (<Publisher: A>, 4.5) # (5+4)/2
  349. >>> b, b.avg_rating
  350. (<Publisher: B>, 4.0) # 4/1 (book with rating 1 excluded)
  351. The first query asks for the average rating of all a publisher's books for
  352. publisher's that have at least one book with a rating exceeding 3.0. The second
  353. query asks for the average of a publisher's book's ratings for only those
  354. ratings exceeding 3.0.
  355. It's difficult to intuit how the ORM will translate complex querysets into SQL
  356. queries so when in doubt, inspect the SQL with ``str(queryset.query)`` and
  357. write plenty of tests.
  358. ``order_by()``
  359. --------------
  360. Annotations can be used as a basis for ordering. When you
  361. define an ``order_by()`` clause, the aggregates you provide can reference
  362. any alias defined as part of an ``annotate()`` clause in the query.
  363. For example, to order a ``QuerySet`` of books by the number of authors
  364. that have contributed to the book, you could use the following query:
  365. .. code-block:: pycon
  366. >>> Book.objects.annotate(num_authors=Count("authors")).order_by("num_authors")
  367. ``values()``
  368. ------------
  369. Ordinarily, annotations are generated on a per-object basis - an annotated
  370. ``QuerySet`` will return one result for each object in the original
  371. ``QuerySet``. However, when a ``values()`` clause is used to constrain the
  372. columns that are returned in the result set, the method for evaluating
  373. annotations is slightly different. Instead of returning an annotated result
  374. for each result in the original ``QuerySet``, the original results are
  375. grouped according to the unique combinations of the fields specified in the
  376. ``values()`` clause. An annotation is then provided for each unique group;
  377. the annotation is computed over all members of the group.
  378. For example, consider an author query that attempts to find out the average
  379. rating of books written by each author:
  380. .. code-block:: pycon
  381. >>> Author.objects.annotate(average_rating=Avg("book__rating"))
  382. This will return one result for each author in the database, annotated with
  383. their average book rating.
  384. However, the result will be slightly different if you use a ``values()`` clause:
  385. .. code-block:: pycon
  386. >>> Author.objects.values("name").annotate(average_rating=Avg("book__rating"))
  387. In this example, the authors will be grouped by name, so you will only get
  388. an annotated result for each *unique* author name. This means if you have
  389. two authors with the same name, their results will be merged into a single
  390. result in the output of the query; the average will be computed as the
  391. average over the books written by both authors.
  392. Order of ``annotate()`` and ``values()`` clauses
  393. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  394. As with the ``filter()`` clause, the order in which ``annotate()`` and
  395. ``values()`` clauses are applied to a query is significant. If the
  396. ``values()`` clause precedes the ``annotate()``, the annotation will be
  397. computed using the grouping described by the ``values()`` clause.
  398. However, if the ``annotate()`` clause precedes the ``values()`` clause,
  399. the annotations will be generated over the entire query set. In this case,
  400. the ``values()`` clause only constrains the fields that are generated on
  401. output.
  402. For example, if we reverse the order of the ``values()`` and ``annotate()``
  403. clause from our previous example:
  404. .. code-block:: pycon
  405. >>> Author.objects.annotate(average_rating=Avg("book__rating")).values(
  406. ... "name", "average_rating"
  407. ... )
  408. This will now yield one unique result for each author; however, only
  409. the author's name and the ``average_rating`` annotation will be returned
  410. in the output data.
  411. You should also note that ``average_rating`` has been explicitly included
  412. in the list of values to be returned. This is required because of the
  413. ordering of the ``values()`` and ``annotate()`` clause.
  414. If the ``values()`` clause precedes the ``annotate()`` clause, any annotations
  415. will be automatically added to the result set. However, if the ``values()``
  416. clause is applied after the ``annotate()`` clause, you need to explicitly
  417. include the aggregate column.
  418. .. _aggregation-ordering-interaction:
  419. Interaction with ``order_by()``
  420. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  421. Fields that are mentioned in the ``order_by()`` part of a queryset are used
  422. when selecting the output data, even if they are not otherwise specified in the
  423. ``values()`` call. These extra fields are used to group "like" results together
  424. and they can make otherwise identical result rows appear to be separate. This
  425. shows up, particularly, when counting things.
  426. By way of example, suppose you have a model like this::
  427. from django.db import models
  428. class Item(models.Model):
  429. name = models.CharField(max_length=10)
  430. data = models.IntegerField()
  431. If you want to count how many times each distinct ``data`` value appears in an
  432. ordered queryset, you might try this::
  433. items = Item.objects.order_by("name")
  434. # Warning: not quite correct!
  435. items.values("data").annotate(Count("id"))
  436. ...which will group the ``Item`` objects by their common ``data`` values and
  437. then count the number of ``id`` values in each group. Except that it won't
  438. quite work. The ordering by ``name`` will also play a part in the grouping, so
  439. this query will group by distinct ``(data, name)`` pairs, which isn't what you
  440. want. Instead, you should construct this queryset::
  441. items.values("data").annotate(Count("id")).order_by()
  442. ...clearing any ordering in the query. You could also order by, say, ``data``
  443. without any harmful effects, since that is already playing a role in the
  444. query.
  445. This behavior is the same as that noted in the queryset documentation for
  446. :meth:`~django.db.models.query.QuerySet.distinct` and the general rule is the
  447. same: normally you won't want extra columns playing a part in the result, so
  448. clear out the ordering, or at least make sure it's restricted only to those
  449. fields you also select in a ``values()`` call.
  450. .. note::
  451. You might reasonably ask why Django doesn't remove the extraneous columns
  452. for you. The main reason is consistency with ``distinct()`` and other
  453. places: Django **never** removes ordering constraints that you have
  454. specified (and we can't change those other methods' behavior, as that
  455. would violate our :doc:`/misc/api-stability` policy).
  456. Aggregating annotations
  457. -----------------------
  458. You can also generate an aggregate on the result of an annotation. When you
  459. define an ``aggregate()`` clause, the aggregates you provide can reference
  460. any alias defined as part of an ``annotate()`` clause in the query.
  461. For example, if you wanted to calculate the average number of authors per
  462. book you first annotate the set of books with the author count, then
  463. aggregate that author count, referencing the annotation field:
  464. .. code-block:: pycon
  465. >>> from django.db.models import Avg, Count
  466. >>> Book.objects.annotate(num_authors=Count("authors")).aggregate(Avg("num_authors"))
  467. {'num_authors__avg': 1.66}
  468. Aggregating on empty querysets or groups
  469. ----------------------------------------
  470. When an aggregation is applied to an empty queryset or grouping, the result
  471. defaults to its :ref:`default <aggregate-default>` parameter, typically
  472. ``None``. This behavior occurs because aggregate functions return ``NULL`` when
  473. the executed query returns no rows.
  474. You can specify a return value by providing the :ref:`default
  475. <aggregate-default>` argument for most aggregations. However, since
  476. :class:`~django.db.models.Count` does not support the :ref:`default
  477. <aggregate-default>` argument, it will always return ``0`` for empty querysets
  478. or groups.
  479. For example, assuming that no book contains *web* in its name, calculating the
  480. total price for this book set would return ``None`` since there are no matching
  481. rows to compute the :class:`~django.db.models.Sum` aggregation on:
  482. .. code-block:: pycon
  483. >>> from django.db.models import Sum
  484. >>> Book.objects.filter(name__contains="web").aggregate(Sum("price"))
  485. {"price__sum": None}
  486. However, the :ref:`default <aggregate-default>` argument can be set when
  487. calling :class:`~django.db.models.Sum` to return a different default value if
  488. no books can be found:
  489. .. code-block:: pycon
  490. >>> Book.objects.filter(name__contains="web").aggregate(Sum("price", default=0))
  491. {"price__sum": Decimal("0")}
  492. Under the hood, the :ref:`default <aggregate-default>` argument is implemented
  493. by wrapping the aggregate function with
  494. :class:`~django.db.models.functions.Coalesce`.