aggregation.txt 17 KB

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