aggregation.txt 23 KB

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