aggregation.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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)
  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. # All the following queries involve traversing the Book<->Publisher
  53. # many-to-many relationship backward
  54. # Each publisher, each with a count of books as a "num_books" attribute.
  55. >>> from django.db.models import Count
  56. >>> pubs = Publisher.objects.annotate(num_books=Count('book'))
  57. >>> pubs
  58. [<Publisher BaloneyPress>, <Publisher SalamiPress>, ...]
  59. >>> pubs[0].num_books
  60. 73
  61. # The top 5 publishers, in order by number of books.
  62. >>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
  63. >>> pubs[0].num_books
  64. 1323
  65. Generating aggregates over a QuerySet
  66. =====================================
  67. Django provides two ways to generate aggregates. The first way is to generate
  68. summary values over an entire ``QuerySet``. For example, say you wanted to
  69. calculate the average price of all books available for sale. Django's query
  70. syntax provides a means for describing the set of all books::
  71. >>> Book.objects.all()
  72. What we need is a way to calculate summary values over the objects that
  73. belong to this ``QuerySet``. This is done by appending an ``aggregate()``
  74. clause onto the ``QuerySet``::
  75. >>> from django.db.models import Avg
  76. >>> Book.objects.all().aggregate(Avg('price'))
  77. {'price__avg': 34.35}
  78. The ``all()`` is redundant in this example, so this could be simplified to::
  79. >>> Book.objects.aggregate(Avg('price'))
  80. {'price__avg': 34.35}
  81. The argument to the ``aggregate()`` clause describes the aggregate value that
  82. we want to compute - in this case, the average of the ``price`` field on the
  83. ``Book`` model. A list of the aggregate functions that are available can be
  84. found in the :ref:`QuerySet reference <aggregation-functions>`.
  85. ``aggregate()`` is a terminal clause for a ``QuerySet`` that, when invoked,
  86. returns a dictionary of name-value pairs. The name is an identifier for the
  87. aggregate value; the value is the computed aggregate. The name is
  88. automatically generated from the name of the field and the aggregate function.
  89. If you want to manually specify a name for the aggregate value, you can do so
  90. by providing that name when you specify the aggregate clause::
  91. >>> Book.objects.aggregate(average_price=Avg('price'))
  92. {'average_price': 34.35}
  93. If you want to generate more than one aggregate, you just add another
  94. argument to the ``aggregate()`` clause. So, if we also wanted to know
  95. the maximum and minimum price of all books, we would issue the query::
  96. >>> from django.db.models import Avg, Max, Min
  97. >>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
  98. {'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}
  99. Generating aggregates for each item in a QuerySet
  100. =================================================
  101. The second way to generate summary values is to generate an independent
  102. summary for each object in a ``QuerySet``. For example, if you are retrieving
  103. a list of books, you may want to know how many authors contributed to
  104. each book. Each Book has a many-to-many relationship with the Author; we
  105. want to summarize this relationship for each book in the ``QuerySet``.
  106. Per-object summaries can be generated using the ``annotate()`` clause.
  107. When an ``annotate()`` clause is specified, each object in the ``QuerySet``
  108. will be annotated with the specified values.
  109. The syntax for these annotations is identical to that used for the
  110. ``aggregate()`` clause. Each argument to ``annotate()`` describes an
  111. aggregate that is to be calculated. For example, to annotate books with
  112. the number of authors:
  113. .. code-block:: python
  114. # Build an annotated queryset
  115. >>> from django.db.models import Count
  116. >>> q = Book.objects.annotate(Count('authors'))
  117. # Interrogate the first object in the queryset
  118. >>> q[0]
  119. <Book: The Definitive Guide to Django>
  120. >>> q[0].authors__count
  121. 2
  122. # Interrogate the second object in the queryset
  123. >>> q[1]
  124. <Book: Practical Django Projects>
  125. >>> q[1].authors__count
  126. 1
  127. As with ``aggregate()``, the name for the annotation is automatically derived
  128. from the name of the aggregate function and the name of the field being
  129. aggregated. You can override this default name by providing an alias when you
  130. specify the annotation::
  131. >>> q = Book.objects.annotate(num_authors=Count('authors'))
  132. >>> q[0].num_authors
  133. 2
  134. >>> q[1].num_authors
  135. 1
  136. Unlike ``aggregate()``, ``annotate()`` is *not* a terminal clause. The output
  137. of the ``annotate()`` clause is a ``QuerySet``; this ``QuerySet`` can be
  138. modified using any other ``QuerySet`` operation, including ``filter()``,
  139. ``order_by()``, or even additional calls to ``annotate()``.
  140. Joins and aggregates
  141. ====================
  142. So far, we have dealt with aggregates over fields that belong to the
  143. model being queried. However, sometimes the value you want to aggregate
  144. will belong to a model that is related to the model you are querying.
  145. When specifying the field to be aggregated in an aggregate function, Django
  146. will allow you to use the same :ref:`double underscore notation
  147. <field-lookups-intro>` that is used when referring to related fields in
  148. filters. Django will then handle any table joins that are required to retrieve
  149. and aggregate the related value.
  150. For example, to find the price range of books offered in each store,
  151. you could use the annotation::
  152. >>> from django.db.models import Max, Min
  153. >>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))
  154. This tells Django to retrieve the ``Store`` model, join (through the
  155. many-to-many relationship) with the ``Book`` model, and aggregate on the
  156. price field of the book model to produce a minimum and maximum value.
  157. The same rules apply to the ``aggregate()`` clause. If you wanted to
  158. know the lowest and highest price of any book that is available for sale
  159. in a store, you could use the aggregate::
  160. >>> Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price'))
  161. Join chains can be as deep as you require. For example, to extract the
  162. age of the youngest author of any book available for sale, you could
  163. issue the query::
  164. >>> Store.objects.aggregate(youngest_age=Min('books__authors__age'))
  165. Following relationships backwards
  166. ---------------------------------
  167. In a way similar to :ref:`lookups-that-span-relationships`, aggregations and
  168. annotations on fields of models or models that are related to the one you are
  169. querying can include traversing "reverse" relationships. The lowercase name
  170. of related models and double-underscores are used here too.
  171. For example, we can ask for all publishers, annotated with their respective
  172. total book stock counters (note how we use ``'book'`` to specify the
  173. ``Publisher`` -> ``Book`` reverse foreign key hop)::
  174. >>> from django.db.models import Count, Min, Sum, Avg
  175. >>> Publisher.objects.annotate(Count('book'))
  176. (Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute
  177. called ``book__count``.)
  178. We can also ask for the oldest book of any of those managed by every publisher::
  179. >>> Publisher.objects.aggregate(oldest_pubdate=Min('book__pubdate'))
  180. (The resulting dictionary will have a key called ``'oldest_pubdate'``. If no
  181. such alias were specified, it would be the rather long ``'book__pubdate__min'``.)
  182. This doesn't apply just to foreign keys. It also works with many-to-many
  183. relations. For example, we can ask for every author, annotated with the total
  184. number of pages considering all the books he/she has (co-)authored (note how we
  185. use ``'book'`` to specify the ``Author`` -> ``Book`` reverse many-to-many hop)::
  186. >>> Author.objects.annotate(total_pages=Sum('book__pages'))
  187. (Every ``Author`` in the resulting ``QuerySet`` will have an extra attribute
  188. called ``total_pages``. If no such alias were specified, it would be the rather
  189. long ``book__pages__sum``.)
  190. Or ask for the average rating of all the books written by author(s) we have on
  191. file::
  192. >>> Author.objects.aggregate(average_rating=Avg('book__rating'))
  193. (The resulting dictionary will have a key called ``'average__rating'``. If no
  194. such alias were specified, it would be the rather long ``'book__rating__avg'``.)
  195. Aggregations and other QuerySet clauses
  196. =======================================
  197. ``filter()`` and ``exclude()``
  198. ------------------------------
  199. Aggregates can also participate in filters. Any ``filter()`` (or
  200. ``exclude()``) applied to normal model fields will have the effect of
  201. constraining the objects that are considered for aggregation.
  202. When used with an ``annotate()`` clause, a filter has the effect of
  203. constraining the objects for which an annotation is calculated. For example,
  204. you can generate an annotated list of all books that have a title starting
  205. with "Django" using the query::
  206. >>> from django.db.models import Count, Avg
  207. >>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
  208. When used with an ``aggregate()`` clause, a filter has the effect of
  209. constraining the objects over which the aggregate is calculated.
  210. For example, you can generate the average price of all books with a
  211. title that starts with "Django" using the query::
  212. >>> Book.objects.filter(name__startswith="Django").aggregate(Avg('price'))
  213. Filtering on annotations
  214. ~~~~~~~~~~~~~~~~~~~~~~~~
  215. Annotated values can also be filtered. The alias for the annotation can be
  216. used in ``filter()`` and ``exclude()`` clauses in the same way as any other
  217. model field.
  218. For example, to generate a list of books that have more than one author,
  219. you can issue the query::
  220. >>> Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)
  221. This query generates an annotated result set, and then generates a filter
  222. based upon that annotation.
  223. Order of ``annotate()`` and ``filter()`` clauses
  224. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  225. When developing a complex query that involves both ``annotate()`` and
  226. ``filter()`` clauses, particular attention should be paid to the order
  227. in which the clauses are applied to the ``QuerySet``.
  228. When an ``annotate()`` clause is applied to a query, the annotation is
  229. computed over the state of the query up to the point where the annotation
  230. is requested. The practical implication of this is that ``filter()`` and
  231. ``annotate()`` are not commutative operations -- that is, there is a
  232. difference between the query::
  233. >>> Publisher.objects.annotate(num_books=Count('book')).filter(book__rating__gt=3.0)
  234. and the query::
  235. >>> Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
  236. Both queries will return a list of publishers that have at least one good
  237. book (i.e., a book with a rating exceeding 3.0). However, the annotation in
  238. the first query will provide the total number of all books published by the
  239. publisher; the second query will only include good books in the annotated
  240. count. In the first query, the annotation precedes the filter, so the
  241. filter has no effect on the annotation. In the second query, the filter
  242. precedes the annotation, and as a result, the filter constrains the objects
  243. considered when calculating the annotation.
  244. ``order_by()``
  245. --------------
  246. Annotations can be used as a basis for ordering. When you
  247. define an ``order_by()`` clause, the aggregates you provide can reference
  248. any alias defined as part of an ``annotate()`` clause in the query.
  249. For example, to order a ``QuerySet`` of books by the number of authors
  250. that have contributed to the book, you could use the following query::
  251. >>> Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
  252. ``values()``
  253. ------------
  254. Ordinarily, annotations are generated on a per-object basis - an annotated
  255. ``QuerySet`` will return one result for each object in the original
  256. ``QuerySet``. However, when a ``values()`` clause is used to constrain the
  257. columns that are returned in the result set, the method for evaluating
  258. annotations is slightly different. Instead of returning an annotated result
  259. for each result in the original ``QuerySet``, the original results are
  260. grouped according to the unique combinations of the fields specified in the
  261. ``values()`` clause. An annotation is then provided for each unique group;
  262. the annotation is computed over all members of the group.
  263. For example, consider an author query that attempts to find out the average
  264. rating of books written by each author:
  265. >>> Author.objects.annotate(average_rating=Avg('book__rating'))
  266. This will return one result for each author in the database, annotated with
  267. their average book rating.
  268. However, the result will be slightly different if you use a ``values()`` clause::
  269. >>> Author.objects.values('name').annotate(average_rating=Avg('book__rating'))
  270. In this example, the authors will be grouped by name, so you will only get
  271. an annotated result for each *unique* author name. This means if you have
  272. two authors with the same name, their results will be merged into a single
  273. result in the output of the query; the average will be computed as the
  274. average over the books written by both authors.
  275. Order of ``annotate()`` and ``values()`` clauses
  276. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  277. As with the ``filter()`` clause, the order in which ``annotate()`` and
  278. ``values()`` clauses are applied to a query is significant. If the
  279. ``values()`` clause precedes the ``annotate()``, the annotation will be
  280. computed using the grouping described by the ``values()`` clause.
  281. However, if the ``annotate()`` clause precedes the ``values()`` clause,
  282. the annotations will be generated over the entire query set. In this case,
  283. the ``values()`` clause only constrains the fields that are generated on
  284. output.
  285. For example, if we reverse the order of the ``values()`` and ``annotate()``
  286. clause from our previous example::
  287. >>> Author.objects.annotate(average_rating=Avg('book__rating')).values('name', 'average_rating')
  288. This will now yield one unique result for each author; however, only
  289. the author's name and the ``average_rating`` annotation will be returned
  290. in the output data.
  291. You should also note that ``average_rating`` has been explicitly included
  292. in the list of values to be returned. This is required because of the
  293. ordering of the ``values()`` and ``annotate()`` clause.
  294. If the ``values()`` clause precedes the ``annotate()`` clause, any annotations
  295. will be automatically added to the result set. However, if the ``values()``
  296. clause is applied after the ``annotate()`` clause, you need to explicitly
  297. include the aggregate column.
  298. Interaction with default ordering or ``order_by()``
  299. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  300. Fields that are mentioned in the ``order_by()`` part of a queryset (or which
  301. are used in the default ordering on a model) are used when selecting the
  302. output data, even if they are not otherwise specified in the ``values()``
  303. call. These extra fields are used to group "like" results together and they
  304. can make otherwise identical result rows appear to be separate. This shows up,
  305. particularly, when counting things.
  306. By way of example, suppose you have a model like this::
  307. from django.db import models
  308. class Item(models.Model):
  309. name = models.CharField(max_length=10)
  310. data = models.IntegerField()
  311. class Meta:
  312. ordering = ["name"]
  313. The important part here is the default ordering on the ``name`` field. If you
  314. want to count how many times each distinct ``data`` value appears, you might
  315. try this::
  316. # Warning: not quite correct!
  317. Item.objects.values("data").annotate(Count("id"))
  318. ...which will group the ``Item`` objects by their common ``data`` values and
  319. then count the number of ``id`` values in each group. Except that it won't
  320. quite work. The default ordering by ``name`` will also play a part in the
  321. grouping, so this query will group by distinct ``(data, name)`` pairs, which
  322. isn't what you want. Instead, you should construct this queryset::
  323. Item.objects.values("data").annotate(Count("id")).order_by()
  324. ...clearing any ordering in the query. You could also order by, say, ``data``
  325. without any harmful effects, since that is already playing a role in the
  326. query.
  327. This behavior is the same as that noted in the queryset documentation for
  328. :meth:`~django.db.models.query.QuerySet.distinct` and the general rule is the
  329. same: normally you won't want extra columns playing a part in the result, so
  330. clear out the ordering, or at least make sure it's restricted only to those
  331. fields you also select in a ``values()`` call.
  332. .. note::
  333. You might reasonably ask why Django doesn't remove the extraneous columns
  334. for you. The main reason is consistency with ``distinct()`` and other
  335. places: Django **never** removes ordering constraints that you have
  336. specified (and we can't change those other methods' behavior, as that
  337. would violate our :doc:`/misc/api-stability` policy).
  338. Aggregating annotations
  339. -----------------------
  340. You can also generate an aggregate on the result of an annotation. When you
  341. define an ``aggregate()`` clause, the aggregates you provide can reference
  342. any alias defined as part of an ``annotate()`` clause in the query.
  343. For example, if you wanted to calculate the average number of authors per
  344. book you first annotate the set of books with the author count, then
  345. aggregate that author count, referencing the annotation field::
  346. >>> from django.db.models import Count, Avg
  347. >>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
  348. {'num_authors__avg': 1.66}