aggregation.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. .. _topics-db-aggregation:
  2. =============
  3. Aggregation
  4. =============
  5. .. versionadded:: 1.1
  6. .. currentmodule:: django.db.models
  7. The topic guide on :ref:`Django's database-abstraction API <topics-db-queries`
  8. described the way that you can use Django queries that create,
  9. retrieve, update and delete individual objects. However, sometimes you will
  10. need to retrieve values that are derived by summarizing or *aggregating* a
  11. collection of objects. This topic guide describes the ways that aggregate values
  12. can be generated and returned using Django queries.
  13. Throughout this guide, we'll refer to the following models. These models are
  14. used to track the inventory for a series of online bookstores:
  15. .. _queryset-model-example:
  16. .. code-block:: python
  17. class Author(models.Model):
  18. name = models.CharField(max_length=100)
  19. age = models.IntegerField()
  20. friends = models.ManyToManyField('self', blank=True)
  21. class Publisher(models.Model):
  22. name = models.CharField(max_length=300)
  23. num_awards = models.IntegerField()
  24. class Book(models.Model):
  25. isbn = models.CharField(max_length=9)
  26. name = models.CharField(max_length=300)
  27. pages = models.IntegerField()
  28. price = models.DecimalField(max_digits=10, decimal_places=2)
  29. rating = models.FloatField()
  30. authors = models.ManyToManyField(Author)
  31. publisher = models.ForeignKey(Publisher)
  32. pubdate = models.DateField()
  33. class Store(models.Model):
  34. name = models.CharField(max_length=300)
  35. books = models.ManyToManyField(Book)
  36. Generating aggregates over a QuerySet
  37. =====================================
  38. Django provides two ways to generate aggregates. The first way is to generate
  39. summary values over an entire ``QuerySet``. For example, say you wanted to
  40. calculate the average price of all books available for sale. Django's query
  41. syntax provides a means for describing the set of all books::
  42. >>> Book.objects.all()
  43. What we need is a way to calculate summary values over the objects that
  44. belong to this ``QuerySet``. This is done by appending an ``aggregate()``
  45. clause onto the ``QuerySet``::
  46. >>> from django.db.models import Avg
  47. >>> Book.objects.all().aggregate(Avg('price'))
  48. {'price__avg': 34.35}
  49. The ``all()`` is redundant in this example, so this could be simplified to::
  50. >>> Book.objects.aggregate(Avg('price'))
  51. {'price__avg': 34.35}
  52. The argument to the ``aggregate()`` clause describes the aggregate value that
  53. we want to compute - in this case, the average of the ``price`` field on the
  54. ``Book`` model. A list of the aggregate functions that are available can be
  55. found in the :ref:`QuerySet reference <aggregation-functions>`.
  56. ``aggregate()`` is a terminal clause for a ``QuerySet`` that, when invoked,
  57. returns a dictionary of name-value pairs. The name is an identifier for the
  58. aggregate value; the value is the computed aggregate. The name is
  59. automatically generated from the name of the field and the aggregate function.
  60. If you want to manually specify a name for the aggregate value, you can do so
  61. by providing that name when you specify the aggregate clause::
  62. >>> Book.objects.aggregate(average_price=Avg('price'))
  63. {'average_price': 34.35}
  64. If you want to generate more than one aggregate, you just add another
  65. argument to the ``aggregate()`` clause. So, if we also wanted to know
  66. the maximum and minimum price of all books, we would issue the query::
  67. >>> from django.db.models import Avg, Max, Min, Count
  68. >>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
  69. {'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}
  70. Generating aggregates for each item in a QuerySet
  71. =================================================
  72. The second way to generate summary values is to generate an independent
  73. summary for each object in a ``Queryset``. For example, if you are retrieving
  74. a list of books, you may want to know how many authors contributed to
  75. each book. Each Book has a many-to-many relationship with the Author; we
  76. want to summarize this relationship for each book in the ``QuerySet``.
  77. Per-object summaries can be generated using the ``annotate()`` clause.
  78. When an ``annotate()`` clause is specified, each object in the ``QuerySet``
  79. will be annotated with the specified values.
  80. The syntax for these annotations is identical to that used for the
  81. ``aggregate()`` clause. Each argument to ``annotate()`` describes an
  82. aggregate that is to be calculated. For example, to annotate Books with
  83. the number of authors::
  84. # Build an annotated queryset
  85. >>> q = Book.objects.annotate(Count('authors'))
  86. # Interrogate the first object in the queryset
  87. >>> q[0]
  88. <Book: The Definitive Guide to Django>
  89. >>> q[0].authors__count
  90. 2
  91. # Interrogate the second object in the queryset
  92. >>> q[1]
  93. <Book: Practical Django Projects>
  94. >>> q[1].authors__count
  95. 1
  96. As with ``aggregate()``, the name for the annotation is automatically derived
  97. from the name of the aggregate function and the name of the field being
  98. aggregated. You can override this default name by providing an alias when you
  99. specify the annotation::
  100. >>> q = Book.objects.annotate(num_authors=Count('authors'))
  101. >>> q[0].num_authors
  102. 2
  103. >>> q[1].num_authors
  104. 1
  105. Unlike ``aggregate()``, ``annotate()`` is *not* a terminal clause. The output
  106. of the ``annotate()`` clause is a ``QuerySet``; this ``QuerySet`` can be
  107. modified using any other ``QuerySet`` operation, including ``filter()``,
  108. ``order_by``, or even additional calls to ``annotate()``.
  109. Joins and aggregates
  110. ====================
  111. So far, we have dealt with aggregates over fields that belong to the
  112. model being queries. However, sometimes the value you want to aggregate
  113. will belong to a model that is related to the model you are querying.
  114. When specifying the field to be aggregated in an aggregate functions,
  115. Django will allow you to use the same
  116. :ref:`double underscore notation <field-lookups-intro>` that is used
  117. when referring to related fields in filters. Django will then handle
  118. any table joins that are required to retrieve and aggregate the
  119. related value.
  120. For example, to find the price range of books offered in each store,
  121. you could use the annotation::
  122. >>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))
  123. This tells Django to retrieve the Store model, join (through the
  124. many-to-many relationship) with the Book model, and aggregate on the
  125. price field of the book model to produce a minimum and maximum value.
  126. The same rules apply to the ``aggregate()`` clause. If you wanted to
  127. know the lowest and highest price of any book that is available for sale
  128. in a store, you could use the aggregate::
  129. >>> Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price'))
  130. Join chains can be as deep as you require. For example, to extract the
  131. age of the youngest author of any book available for sale, you could
  132. issue the query::
  133. >>> Store.objects.aggregate(youngest_age=Min('books__authors__age'))
  134. Aggregations and other QuerySet clauses
  135. =======================================
  136. ``filter()`` and ``exclude()``
  137. ------------------------------
  138. Aggregates can also participate in filters. Any ``filter()`` (or
  139. ``exclude()``) applied to normal model fields will have the effect of
  140. constraining the objects that are considered for aggregation.
  141. When used with an ``annotate()`` clause, a filter has the effect of
  142. constraining the objects for which an annotation is calculated. For example,
  143. you can generate an annotated list of all books that have a title starting
  144. with "Django" using the query::
  145. >>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
  146. When used with an ``aggregate()`` clause, a filter has the effect of
  147. constraining the objects over which the aggregate is calculated.
  148. For example, you can generate the average price of all books with a
  149. title that starts with "Django" using the query::
  150. >>> Book.objects.filter(name__startswith="Django").aggregate(Avg('price'))
  151. Filtering on annotations
  152. ~~~~~~~~~~~~~~~~~~~~~~~~
  153. Annotated values can also be filtered. The alias for the annotation can be
  154. used in ``filter()`` and ``exclude()`` clauses in the same way as any other
  155. model field.
  156. For example, to generate a list of books that have more than one author,
  157. you can issue the query::
  158. >>> Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)
  159. This query generates an annotated result set, and then generates a filter
  160. based upon that annotation.
  161. Order of ``annotate()`` and ``filter()`` clauses
  162. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  163. When developing a complex query that involves both ``annotate()`` and
  164. ``filter()`` clauses, particular attention should be paid to the order
  165. in which the clauses are applied to the ``QuerySet``.
  166. When an ``annotate()`` clause is applied to a query, the annotation is
  167. computed over the state of the query up to the point where the annotation
  168. is requested. The practical implication of this is that ``filter()`` and
  169. ``annotate()`` are not transitive operations -- that is, there is a
  170. difference between the query::
  171. >>> Publisher.objects.annotate(num_books=Count('book')).filter(book__rating__gt=3.0)
  172. and the query::
  173. >>> Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
  174. Both queries will return a list of Publishers that have at least one good
  175. book (i.e., a book with a rating exceeding 3.0). However, the annotation in
  176. the first query will provide the total number of all books published by the
  177. publisher; the second query will only include good books in the annotated
  178. count. In the first query, the annotation precedes the filter, so the
  179. filter has no effect on the annotation. In the second query, the filter
  180. preceeds the annotation, and as a result, the filter constrains the objects
  181. considered when calculating the annotation.
  182. ``order_by()``
  183. --------------
  184. Annotations can be used as a basis for ordering. When you
  185. define an ``order_by()`` clause, the aggregates you provide can reference
  186. any alias defined as part of an ``annotate()`` clause in the query.
  187. For example, to order a ``QuerySet`` of books by the number of authors
  188. that have contributed to the book, you could use the following query::
  189. >>> Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
  190. ``values()``
  191. ------------
  192. Ordinarily, annotations are generated on a per-object basis - an annotated
  193. ``QuerySet`` will return one result for each object in the original
  194. ``Queryset``. However, when a ``values()`` clause is used to constrain the
  195. columns that are returned in the result set, the method for evaluating
  196. annotations is slightly different. Instead of returning an annotated result
  197. for each result in the original ``QuerySet``, the original results are
  198. grouped according to the unique combinations of the fields specified in the
  199. ``values()`` clause. An annotation is then provided for each unique group;
  200. the annotation is computed over all members of the group.
  201. For example, consider an author query that attempts to find out the average
  202. rating of books written by each author:
  203. >>> Author.objects.annotate(average_rating=Avg('book__rating'))
  204. This will return one result for each author in the database, annotate with
  205. their average book rating.
  206. However, the result will be slightly different if you use a ``values()`` clause::
  207. >>> Author.objects.values('name').annotate(average_rating=Avg('book__rating'))
  208. In this example, the authors will be grouped by name, so you will only get
  209. an annotated result for each *unique* author name. This means if you have
  210. two authors with the same name, their results will be merged into a single
  211. result in the output of the query; the average will be computed as the
  212. average over the books written by both authors.
  213. Order of ``annotate()`` and ``values()`` clauses
  214. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  215. As with the ``filter()`` clause, the order in which ``annotate()`` and
  216. ``values()`` clauses are applied to a query is significant. If the
  217. ``values()`` clause precedes the ``annotate()``, the annotation will be
  218. computed using the grouping described by the ``values()`` clause.
  219. However, if the ``annotate()`` clause precedes the ``values()`` clause,
  220. the annotations will be generated over the entire query set. In this case,
  221. the ``values()`` clause only constrains the fields that are generated on
  222. output.
  223. For example, if we reverse the order of the ``values()`` and ``annotate()``
  224. clause from our previous example::
  225. >>> Author.objects.annotate(average_rating=Avg('book__rating')).values('name', 'average_rating')
  226. This will now yield one unique result for each author; however, only
  227. the author's name and the ``average_rating`` annotation will be returned
  228. in the output data.
  229. You should also note that ``average_rating`` has been explicitly included
  230. in the list of values to be returned. This is required because of the
  231. ordering of the ``values()`` and ``annotate()`` clause.
  232. If the ``values()`` clause precedes the ``annotate()`` clause, any annotations
  233. will be automatically added to the result set. However, if the ``values()``
  234. clause is applied after the ``annotate()`` clause, you need to explicitly
  235. include the aggregate column.
  236. Aggregating annotations
  237. -----------------------
  238. You can also generate an aggregate on the result of an annotation. When you
  239. define an ``aggregate()`` clause, the aggregates you provide can reference
  240. any alias defined as part of an ``annotate()`` clause in the query.
  241. For example, if you wanted to calculate the average number of authors per
  242. book you first annotate the set of books with the author count, then
  243. aggregate that author count, referencing the annotation field::
  244. >>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
  245. {'num_authors__avg': 1.66}