Django 中的aggregate() 与 annotate()
Django 的QuerySet
有两个方法,annotate
和aggregate
。文档说:
与aggregate()不同,annotate()不是终止子句。 annotate() 子句的输出是一个查询集。 https: //docs.djangoproject.com/en/4.1/topics/db/aggregation/#generate-aggregates-for-each-item-in-a-queryset
它们之间还有其他区别吗?如果不是,那为什么会有aggregate
存在呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会关注示例查询而不是文档中的引用。
Aggregate
计算整个查询集的值。Annotate
计算查询集中每个项目的汇总值。聚合
返回一个字典,其中包含查询集中所有图书的平均价格。
注释
q
是书籍的查询集,但每本书都标注了作者数量。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.Aggregation
Returns a dictionary containing the average price of all books in the queryset.
Annotation
q
is the queryset of books, but each book has been annotated with the number of authors.聚合
聚合整个查询集的生成结果(摘要)值。
对行集进行聚合操作以从行集中获取单个值。(例如行集中所有价格的总和)。聚合应用于整个查询集,并在整个查询集中生成结果(摘要)值。
在模型中:
在 Shell 中:
注释
Annotate 为 QuerySet 中的每个对象生成独立的摘要。(我们可以说它迭代 QuerySet 中的每个对象并应用操作)
在模型中:
在视图中:
在视图中它将计算每个视频的点赞数
Aggregate
Aggregate generate result (summary) values over an entire QuerySet.
Aggregate operate over the rowset to get a single value from the rowset.(For example sum of all prices in the rowset). Aggregate is applied on entire QuerySet and it generate result (summary) values over an entire QuerySet.
In Model:
In Shell:
Annotate
Annotate generate an independent summary for each object in a QuerySet.(We can say it iterate each object in a QuerySet and apply operation)
In Model:
In View:
In view it will count the likes for each video
这是主要的区别,但聚合的工作范围也比注释更大。注释本质上与查询集中的各个项目相关。如果您在多对多字段之类的字段上运行
Count
注释,您将为查询集的每个成员获得单独的计数(作为添加的属性)。但是,如果您要对聚合执行相同的操作,它将尝试对查询集的每个成员(甚至重复项)上的每个关系进行计数,并将其仅作为一个值返回。That's the main difference, but aggregates also work on a grander scale than annotations. Annotations are inherently related to individual items in a queryset. If you run an
Count
annotation on a something like a many-to-many field, you'll get a separate count for each member of the queryset (as an added attribute). If you were to do the same with an aggregation, however, it would attempt to count every relationship on every member of the queryset, even duplicates, and return that as just one value.聚合() 可以计算当前模型列的所有值。 *返回字典。
annotate() 可以计算通过外键访问子模型的列。 *返回一个QuerySet。
*Avg(),Count(), Max(),Min(), Sum() 等可以与
aggregate 一起使用()
和annotate()
。例如,下面有
Category
和Product
模型:并且,下面有
Category
和Product
管理员:并且,有以下 2 个类别:
并且,有以下 5 种产品:
并且,下面有
test
视图:首先,我解释一下
聚合()
。aggregate():
现在,我运行
test
视图,其中包含列id
、category
和price
在 Avg() 中,Count(), Max(), Min() 和 Sum() inaggregate()
如下所示:然后,这些字典下面是在控制台上输出:
并且,
aggregate()
可以接受任意顺序的多种列和函数、多个相同类型的列和函数以及没有列和函数,如下所示。 *将多个相同类型的列和函数合并为一个,并且没有列和函数得到空字典:然后,在控制台上输出以下这些字典:
And、
Max()
和Min下面的 ()
可以接受非数字类型:然后,下面这些字典将在控制台上输出:
But、
Avg()
和Sum()
以下不能接受非数字类型:因此,会出现以下错误:
并且,您可以更改默认键名称,如下所示:
然后,默认键名称更改如下:
接下来,我解释一下
注释()。
annotate():
现在,我运行
test
视图,其中包含列product__id
、product__category
和product__price
在Avg()
、Count()
、Max()
、Min()
和 <代码>Sum() 中annotate()
如下所示。 *您需要将__avg
、__count
、__max
、__min
和__sum
放入product__id
、product__category
和product__price
用于Avg()
、Count()
、<代码>最大(),分别是Min()
和Sum()
:然后,在控制台上输出以下内容:
并且,不带 order_by('pk') 下面使订单后代:
然后,顺序是后代如下所示:
并且,下面的空
annotate()
有id
和name
属性:然后,下面这些控制台输出:
但是,下面的空
annotate()
没有__avg
、__count
、__max
,__min
和 __sum 属性如下所示:因此,出现以下错误:
并且下面的
Max()
和Min()
可以接受非数字类型:然后,在控制台上输出以下内容:
但是,下面的
Avg()
和Sum()
不能接受非数字类型:因此,出现以下错误:
并且,您可以更改默认属性名称,如下所示:
然后,以下内容将在控制台上输出:
aggregate() can calculates all values of the current model's column. *A dictionary is returned.
annotate() can calculates all values of the child model's column accessed by foreign key. *A QuerySet is returned.
*Avg(), Count(), Max(), Min(), Sum() and so on can be used with
aggregate()
andannotate()
.For example, there are
Category
andProduct
models below:And, there are
Category
andProduct
admins below:And, there are 2 categories below:
And, there are 5 products below:
And, there is
test
view below:First, I explain about
aggregate()
.aggregate():
Now, I run
test
view which has the columnsid
,category
andprice
in Avg(), Count(), Max(), Min() and Sum() inaggregate()
as shown below:Then, these dictionaries below are outputted on console:
And,
aggregate()
can accept multiple kinds of columns and functions in any order, the multiple same kind of columns and functions and no columns and functions as shown below. *The multiple same kind of columns and functions are made into one and no columns and functions get an empty dictionary:Then, these dictionaries below are outputted on console:
And,
Max()
andMin()
below can accept non-numeric types:Then, these dictionaries below are outputted on console:
But,
Avg()
andSum()
below cannot accept non-numeric types:So, the errors below occur:
And, you can change the default key names as shown below:
Then, the default key names are changed as shown below:
Next, I explain about
annotate()
.annotate():
Now, I run
test
view which has the columnsproduct__id
,product__category
andproduct__price
inAvg()
,Count()
,Max()
,Min()
andSum()
inannotate()
as shown below. *You need to put__avg
,__count
,__max
,__min
and__sum
toproduct__id
,product__category
andproduct__price
forAvg()
,Count()
,Max()
,Min()
andSum()
respectively:Then, these below are outputted on console:
And, the query without order_by('pk') below makes the order descendant:
Then, the order is descendant as shown below:
And, empty
annotate()
below hasid
andname
attributes:Then, these below are outputted on console:
But, empty
annotate()
below doesn't have__avg
,__count
,__max
,__min
and__sum
attributes as shown below:So, the errors below occur:
And,
Max()
andMin()
below can accept non-numeric types:Then, these below are outputted on console:
But,
Avg()
andSum()
below cannot accept non-numeric types:So, the errors below occur:
And, you can change the default attribute names as shown below:
Then, these below are outputted on console: