本文介绍了Django的注释和聚合方法的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django的 QuerySet 有两种方法, annotate aggregate 。文档说:

Django's QuerySet has two methods, annotate and aggregate. The documentation says that:

它们之间有什么区别吗?如果没有,那么为什么聚合存在?

Is there any other difference between them? If not, then why does aggregate exist?

推荐答案

在示例查询上,而不是从文档中引用。 Aggregate 计算整个查询集的值。 注释在查询集中计算每项的汇总值。

I would focus on the example queries rather than your quote from the documentation. Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset.

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

返回包含查询器中所有图书的平均价格的字典。

Returns a dictionary containing the average price of all books in the queryset.

>>> q = Book.objects.annotate(num_authors=Count('authors'))
>>> q[0].num_authors
2
>>> q[1].num_authors
1

q 是图书的查询,但每本书都已经注明了作者的数量。

q is the queryset of books, but each book has been annotated with the number of authors.

这篇关于Django的注释和聚合方法的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:19