Django注释对于平均值,最小值/最大值等非常有用.它也可以计数.那么生成相同的SQL就好像我在查询集上使用旧的.count()一样?或者它在某些情况下会生成更高效的SQL吗?还是更糟糕的SQL?
对不起,为了澄清,我的意思是将count()操作与聚合(Count('id'))进行比较,其中id是表的PK.
所以,我相信Brian有正确的答案.简而言之,count()只是aggregate()的一个特例.
Bri*_*ket 10
调用queryset的.count()
方法最终会调用Count()
.
特别是:
django.db.models.QuerySet.count()
调用的
django.db.models.sql.Query.get_count()
调用
django.db.models.sql.Query.add_count_column()
,它会添加
django.db.models.sql.aggregates.Count
到查询中.
两者之间的主要区别在于,当您Count
直接使用时,您指定要计数的字段,而当您调用查询集.count()
时,这将导致SELECT COUNT(*)...
(除非您还使用distinct()或限制字段时select子句,在这种情况下它更复杂).
苹果和橙子。.count()
对当前查询集进行 SQL 计数。在Count
骨料,但是,你运行的查询集上指定关系的计数。
Pizza.objects.count() # Total amount of pizzas
Pizza.objects.aggregate(topping_count=Count('toppings')) # Total amount of toppings associated to a pizza
Pizza.objects.annotate(topping_count=Count('toppings')) # Total amount of toppings on each pizza
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6884 次 |
最近记录: |