聚合

Django 数据库抽象 API 描述了使用 Django queries 来增删查改单个对象的方法。 然而,有时候你要获取的值需要根据一组对象聚合后才能得到。这个主题指南描述了如何使用 Django queries 来生成和返回聚合值的方法。

整篇指南我们将引用以下模型。这些模型用来记录多个网上书店的库存。

  1. from django.db import models
  2. class Author(models.Model):
  3. name = models.CharField(max_length=100)
  4. age = models.IntegerField()
  5. class Publisher(models.Model):
  6. name = models.CharField(max_length=300)
  7. class Book(models.Model):
  8. name = models.CharField(max_length=300)
  9. pages = models.IntegerField()
  10. price = models.DecimalField(max_digits=10, decimal_places=2)
  11. rating = models.FloatField()
  12. authors = models.ManyToManyField(Author)
  13. publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
  14. pubdate = models.DateField()
  15. class Store(models.Model):
  16. name = models.CharField(max_length=300)
  17. books = models.ManyToManyField(Book)

速查表

下面是根据以上模型执行常见的聚合查询:

  1. # Total number of books.
  2. >>> Book.objects.count()
  3. 2452
  4. # Total number of books with publisher=BaloneyPress
  5. >>> Book.objects.filter(publisher__name="BaloneyPress").count()
  6. 73
  7. # Average price across all books, provide default to be returned instead
  8. # of None if no books exist.
  9. >>> from django.db.models import Avg
  10. >>> Book.objects.aggregate(Avg("price", default=0))
  11. {'price__avg': 34.35}
  12. # Max price across all books, provide default to be returned instead of
  13. # None if no books exist.
  14. >>> from django.db.models import Max
  15. >>> Book.objects.aggregate(Max("price", default=0))
  16. {'price__max': Decimal('81.20')}
  17. # Difference between the highest priced book and the average price of all books.
  18. >>> from django.db.models import FloatField
  19. >>> Book.objects.aggregate(
  20. ... price_diff=Max("price", output_field=FloatField()) - Avg("price")
  21. ... )
  22. {'price_diff': 46.85}
  23. # All the following queries involve traversing the Book<->Publisher
  24. # foreign key relationship backwards.
  25. # Each publisher, each with a count of books as a "num_books" attribute.
  26. >>> from django.db.models import Count
  27. >>> pubs = Publisher.objects.annotate(num_books=Count("book"))
  28. >>> pubs
  29. <QuerySet [<Publisher: BaloneyPress>, <Publisher: SalamiPress>, ...]>
  30. >>> pubs[0].num_books
  31. 73
  32. # Each publisher, with a separate count of books with a rating above and below 5
  33. >>> from django.db.models import Q
  34. >>> above_5 = Count("book", filter=Q(book__rating__gt=5))
  35. >>> below_5 = Count("book", filter=Q(book__rating__lte=5))
  36. >>> pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)
  37. >>> pubs[0].above_5
  38. 23
  39. >>> pubs[0].below_5
  40. 12
  41. # The top 5 publishers, in order by number of books.
  42. >>> pubs = Publisher.objects.annotate(num_books=Count("book")).order_by("-num_books")[:5]
  43. >>> pubs[0].num_books
  44. 1323

QuerySet 上生成聚合

Django provides two ways to generate aggregates. The first way is to generate summary values over an entire QuerySet. For example, say you wanted to calculate the average price of all books available for sale. Django’s query syntax provides a means for describing the set of all books:

  1. >>> Book.objects.all()

What we need is a way to calculate summary values over the objects that belong to this QuerySet. This is done by appending an aggregate() clause onto the QuerySet:

  1. >>> from django.db.models import Avg
  2. >>> Book.objects.all().aggregate(Avg("price"))
  3. {'price__avg': 34.35}

The all() is redundant in this example, so this could be simplified to:

  1. >>> Book.objects.aggregate(Avg("price"))
  2. {'price__avg': 34.35}

传递给 aggregate() 的参数描述了我们想要计算的聚合值。在这个例子里,要计算的就是 Book 模型上的 price 字段的平均值。可用的聚合函数列表可以在 QuerySet reference 中找到。

aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs. The name is an identifier for the aggregate value; the value is the computed aggregate. The name is automatically generated from the name of the field and the aggregate function. If you want to manually specify a name for the aggregate value, you can do so by providing that name when you specify the aggregate clause:

  1. >>> Book.objects.aggregate(average_price=Avg("price"))
  2. {'average_price': 34.35}

If you want to generate more than one aggregate, you add another argument to the aggregate() clause. So, if we also wanted to know the maximum and minimum price of all books, we would issue the query:

  1. >>> from django.db.models import Avg, Max, Min
  2. >>> Book.objects.aggregate(Avg("price"), Max("price"), Min("price"))
  3. {'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}

QuerySet 中的每一个条目生成聚合

生成值的汇总的另一个办法是为 QuerySet 的每一个对象生成独立汇总。比如,如果你想检索书籍列表,你可能想知道每一本书有多少作者。每一本书与作者有多对多的关系;我们想在 QuerySet 中为每一本书总结这个关系。

使用 annotate() 子句可以生成每一个对象的汇总。当指定 annotate() 子句,QuerySet 中的每一个对象将对指定值进行汇总。

这些汇总语法规则与 aggregate() 子句的规则相同。annotate() 的每一个参数描述了一个要计算的聚合。比如,注解(annotate)所有书的所有作者:

  1. # Build an annotated queryset
  2. >>> from django.db.models import Count
  3. >>> q = Book.objects.annotate(Count("authors"))
  4. # Interrogate the first object in the queryset
  5. >>> q[0]
  6. <Book: The Definitive Guide to Django>
  7. >>> q[0].authors__count
  8. 2
  9. # Interrogate the second object in the queryset
  10. >>> q[1]
  11. <Book: Practical Django Projects>
  12. >>> q[1].authors__count
  13. 1

As with aggregate(), the name for the annotation is automatically derived from the name of the aggregate function and the name of the field being aggregated. You can override this default name by providing an alias when you specify the annotation:

  1. >>> q = Book.objects.annotate(num_authors=Count("authors"))
  2. >>> q[0].num_authors
  3. 2
  4. >>> q[1].num_authors
  5. 1

aggregate() 不同的是,annotate() 不是终端子句。annotate() 子句的输出就是 QuerySet;这个 QuerySet 被其他 QuerySet 操作进行修改,包括 filter()`, order_by() ,甚至可以对 annotate() 进行额外调用。

组合多个聚合

使用 annotate() 组合多个聚合将产生错误的结果( yield the wrong results ),因为它使用连接(joins)而不是子查询:

  1. >>> book = Book.objects.first()
  2. >>> book.authors.count()
  3. 2
  4. >>> book.store_set.count()
  5. 3
  6. >>> q = Book.objects.annotate(Count("authors"), Count("store"))
  7. >>> q[0].authors__count
  8. 6
  9. >>> q[0].store__count
  10. 6

对大部分聚合来说,没办法避免这个问题,但是,Count 聚合可以使用 distinct 参数来避免:

  1. >>> q = Book.objects.annotate(
  2. ... Count("authors", distinct=True), Count("store", distinct=True)
  3. ... )
  4. >>> q[0].authors__count
  5. 2
  6. >>> q[0].store__count
  7. 3

如有疑问,请检查 SQL 查询!

为了搞清楚你的查询发生了什么问题,你得在 QuerySet 中检查一下``query`` 属性。

连接(Joins)和聚合

到目前为止,我们已经处理了被查询模型字段的聚合。然而,有时候想聚合的值属于你正在查询模型的关联模型。

在聚合函数里面指定聚合的字段时,Django 允许你在过滤相关字段的时候使用相同的双下划线表示法。Django 将处理任何需要检索和聚合的关联值的表连接(table joins)。

For example, to find the price range of books offered in each store, you could use the annotation:

  1. >>> from django.db.models import Max, Min
  2. >>> Store.objects.annotate(min_price=Min("books__price"), max_price=Max("books__price"))

这告诉 Django 去检索 Store 模型,连接(通过多对多关系) Book 模型,并且聚合书籍模型的价格字段来获取最大最小值。

The same rules apply to the aggregate() clause. If you wanted to know the lowest and highest price of any book that is available for sale in any of the stores, you could use the aggregate:

  1. >>> Store.objects.aggregate(min_price=Min("books__price"), max_price=Max("books__price"))

Join chains can be as deep as you require. For example, to extract the age of the youngest author of any book available for sale, you could issue the query:

  1. >>> Store.objects.aggregate(youngest_age=Min("books__authors__age"))

反向关系

类似于 跨关系查询 ,你正在查询的在模型和模型字段上的聚合和注解(annotations)可以包含反向关系。关系模型的小写名和双下划线也可以用在这里。

For example, we can ask for all publishers, annotated with their respective total book stock counters (note how we use 'book' to specify the Publisher -> Book reverse foreign key hop):

  1. >>> from django.db.models import Avg, Count, Min, Sum
  2. >>> Publisher.objects.annotate(Count("book"))

(查询结果里的每一个 Publisher 会有多余的属性—— book__count 。)

We can also ask for the oldest book of any of those managed by every publisher:

  1. >>> Publisher.objects.aggregate(oldest_pubdate=Min("book__pubdate"))

(结果字典中会有一个叫 'oldest_pubdate' 的键。如果没有指定这样的别名,它将会是一个很长的名字 'book__pubdate__min' 。)

This doesn’t apply just to foreign keys. It also works with many-to-many relations. For example, we can ask for every author, annotated with the total number of pages considering all the books the author has (co-)authored (note how we use 'book' to specify the Author -> Book reverse many-to-many hop):

  1. >>> Author.objects.annotate(total_pages=Sum("book__pages"))

(结果集里的每一个 Author 会有一个额外的属性——total_pages)如果没有指定这样的别名,它将会是一个很长的名字 book__pages__sum

Or ask for the average rating of all the books written by author(s) we have on file:

  1. >>> Author.objects.aggregate(average_rating=Avg("book__rating"))

(结果字典会有一个叫 'average_rating' 的键。如果没有指定这样的别名,它将会是一个很长的名字 'book__rating__avg'。)

聚合和其他 QuerySet 子句

filter()exclude()

聚合也可以参与过滤。任何应用于普通模型字段的 filter() (或 exclude())会具有约束被认为是聚合的对象的效果。

When used with an annotate() clause, a filter has the effect of constraining the objects for which an annotation is calculated. For example, you can generate an annotated list of all books that have a title starting with “Django” using the query:

  1. >>> from django.db.models import Avg, Count
  2. >>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count("authors"))

When used with an aggregate() clause, a filter has the effect of constraining the objects over which the aggregate is calculated. For example, you can generate the average price of all books with a title that starts with “Django” using the query:

  1. >>> Book.objects.filter(name__startswith="Django").aggregate(Avg("price"))

过滤注解

注解过的值也可以使用过滤器。注解的别名可以和任何其他模型字段一样使用 filter()exclude() 子句。

For example, to generate a list of books that have more than one author, you can issue the query:

  1. >>> Book.objects.annotate(num_authors=Count("authors")).filter(num_authors__gt=1)

这个查询生成一个注解结果集,然后生成一个基于注解的过滤器。

If you need two annotations with two separate filters you can use the filter argument with any aggregate. For example, to generate a list of authors with a count of highly rated books:

  1. >>> highly_rated = Count("book", filter=Q(book__rating__gte=7))
  2. >>> Author.objects.annotate(num_books=Count("book"), highly_rated_books=highly_rated)

结果集中的每个 Author 都有 num_bookshighly_rated_books 属性。参见 条件聚合

filterQuerySet.filter() 中做选择

避免在单个注解和聚合中使用 filter 语句。使用 QuerySet.filter() 来排除列会很高效。聚合 filter 语句只在使用具有不同条件的相同关系的两个或以上的聚合时有用。

annotate()filter() 子句的顺序

当开发一个涉及 annotate()filter() 子句的复杂查询时,要特别注意应用于 QuerySet 的子句的顺序。

当一个 annotate() 子句应用于查询,会根据查询状态来计算注解,直到请求的注解为止。这实际上意味着 filter()annotate() 不是可交换的操作。

比如:

  • 出版者A有两本评分4和5的书。
  • 出版者B有两本评分1和4的书。
  • 出版者C有一本评分1的书。

Here’s an example with the Count aggregate:

  1. >>> a, b = Publisher.objects.annotate(num_books=Count("book", distinct=True)).filter(
  2. ... book__rating__gt=3.0
  3. ... )
  4. >>> a, a.num_books
  5. (<Publisher: A>, 2)
  6. >>> b, b.num_books
  7. (<Publisher: B>, 2)
  8. >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count("book"))
  9. >>> a, a.num_books
  10. (<Publisher: A>, 2)
  11. >>> b, b.num_books
  12. (<Publisher: B>, 1)

两个查询返回出版者列表,这些出版者至少有一本评分3的书,因此排除了C。

在第一个查询里,注解优先于过滤器,因此过滤器没有影响注解。distinct=True 用来避免 a query bug

第二个查询每个发布者评分3以上的书籍数量。过滤器优先于注解,因此过滤器约束计算注解时考虑的对象。

Here’s another example with the Avg aggregate:

  1. >>> a, b = Publisher.objects.annotate(avg_rating=Avg("book__rating")).filter(
  2. ... book__rating__gt=3.0
  3. ... )
  4. >>> a, a.avg_rating
  5. (<Publisher: A>, 4.5) # (5+4)/2
  6. >>> b, b.avg_rating
  7. (<Publisher: B>, 2.5) # (1+4)/2
  8. >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(
  9. ... avg_rating=Avg("book__rating")
  10. ... )
  11. >>> a, a.avg_rating
  12. (<Publisher: A>, 4.5) # (5+4)/2
  13. >>> b, b.avg_rating
  14. (<Publisher: B>, 4.0) # 4/1 (book with rating 1 excluded)

第一个查询请求至少有一本评分3以上的书籍的出版者的书籍平均分。第二个查询只请求评分3以上的作者书籍的平均评分。

很难凭直觉了解ORM如何将复杂的查询集转化为SQL查询,因此当有疑问时,请使用 str(queryset.query)` 检查SQL,并写大量的测试。

order_by()

注解可以当做基本排序来使用。当你定义了一个 order_by() 子句,你提供的聚合可以引用任何定义为查询中 annotate() 子句的一部分的别名。

For example, to order a QuerySet of books by the number of authors that have contributed to the book, you could use the following query:

  1. >>> Book.objects.annotate(num_authors=Count("authors")).order_by("num_authors")

values()

通常,注解值会添加到每个对象上,即一个被注解的 QuerySet 将会为初始 QuerySet 的每个对象返回一个结果集。然而,当使用 values() 子句来对结果集进行约束时,生成注解值的方法会稍有不同。不是在原始 QuerySet 中对每个对象添加注解并返回,而是根据定义在 values() 子句中的字段组合先对结果进行分组,再对每个单独的分组进行注解,这个注解值是根据分组中所有的对象计算得到的。

下面是一个关于作者的查询例子,查询每个作者所著书的平均评分:

  1. >>> Author.objects.annotate(average_rating=Avg("book__rating"))

这段代码返回的是数据库中的所有作者及其所著书的平均评分。

However, the result will be slightly different if you use a values() clause:

  1. >>> Author.objects.values("name").annotate(average_rating=Avg("book__rating"))

在这个例子中,作者会按名字分组,所以你只能得到不重名的作者分组的注解值。这意味着如果你有两个作者同名,那么他们原本各自的查询结果将被合并到同一个结果中;两个作者的所有评分都将被计算为一个平均分。

annotate()values() 的顺序

和使用 filter() 一样,作用于某个查询的 annotate()values() 子句的顺序非常重要。如果 values() 子句在 annotate() 之前,就会根据 values() 子句产生的分组来计算注解。

然而如果 annotate() 子句在 values() 之前,就会根据整个查询集生成注解。这种情况下,values() 子句只能限制输出的字段。

For example, if we reverse the order of the values() and annotate() clause from our previous example:

  1. >>> Author.objects.annotate(average_rating=Avg("book__rating")).values(
  2. ... "name", "average_rating"
  3. ... )

这段代码将为每个作者添加一个唯一注解,但只有作者姓名和 average_rating 注解会返回在输出结果中。

你应该也会注意 average_rating 已经明确包含在返回的值列表中。这是必需的,因为 values()annotate() 子句的顺序。

如果 values() 子句在 annotate() 子句之前,任何注解将自动添加在结果集中。然而,如果 values() 子句应用在 annotate() 子句之后,则需要显式包含聚合列。

Interaction with order_by()

Fields that are mentioned in the order_by() part of a queryset are used when selecting the output data, even if they are not otherwise specified in the values() call. These extra fields are used to group “like” results together and they can make otherwise identical result rows appear to be separate. This shows up, particularly, when counting things.

举个例子,假设你有这样的模型:

  1. from django.db import models
  2. class Item(models.Model):
  3. name = models.CharField(max_length=10)
  4. data = models.IntegerField()

If you want to count how many times each distinct data value appears in an ordered queryset, you might try this:

  1. items = Item.objects.order_by("name")
  2. # Warning: not quite correct!
  3. items.values("data").annotate(Count("id"))

…which will group the Item objects by their common data values and then count the number of id values in each group. Except that it won’t quite work. The ordering by name will also play a part in the grouping, so this query will group by distinct (data, name) pairs, which isn’t what you want. Instead, you should construct this queryset:

  1. items.values("data").annotate(Count("id")).order_by()

清除任何查询中的排序。你也可以通过 data 排序,没有任何有害影响,因为它已经在查询中发挥了作用。

这个行为与 distinct() 的查询文档指出的行为相同,一般规则是一样的:通常情况下,你不希望额外的列在结果中发挥作用,因此要清除排序,或者至少确保它只限于您在 values() 调用中选择的那些字段。

备注

你可以会问为什么 Django 没有移除无关的列。主要原因就是与 distinct() 和其他地方的一致性:Django从不删除你指定的排序约束(我们不能改变其他方法的行为,因为这会违反我们的应用编程接口的稳定性政策)。

聚合注解

你也可以在注解结果上生成聚合。当你定义 aggregate() 子句时,你提供的聚合可以引用任何定义在查询中 annotate() 子句的别名。

For example, if you wanted to calculate the average number of authors per book you first annotate the set of books with the author count, then aggregate that author count, referencing the annotation field:

  1. >>> from django.db.models import Avg, Count
  2. >>> Book.objects.annotate(num_authors=Count("authors")).aggregate(Avg("num_authors"))
  3. {'num_authors__avg': 1.66}

Aggregating on empty querysets or groups

When an aggregation is applied to an empty queryset or grouping, the result defaults to its default parameter, typically None. This behavior occurs because aggregate functions return NULL when the executed query returns no rows.

You can specify a return value by providing the default argument for most aggregations. However, since Count does not support the default argument, it will always return 0 for empty querysets or groups.

For example, assuming that no book contains web in its name, calculating the total price for this book set would return None since there are no matching rows to compute the Sum aggregation on:

  1. >>> from django.db.models import Sum
  2. >>> Book.objects.filter(name__contains="web").aggregate(Sum("price"))
  3. {"price__sum": None}

However, the default argument can be set when calling Sum to return a different default value if no books can be found:

  1. >>> Book.objects.filter(name__contains="web").aggregate(Sum("price", default=0))
  2. {"price__sum": Decimal("0")}

Under the hood, the default argument is implemented by wrapping the aggregate function with Coalesce.