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