在Django中,无论如何,aggregate(Count())比.count()更快还是更好? [英] In django, is aggregate(Count()) faster or better than .count() in anyway?

查看:90
本文介绍了在Django中,无论如何,aggregate(Count())比.count()更快还是更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django注释非常适合平均值,最小值/最大值等。它也可以计数。那是否生成与我在queryset上使用旧的.count()相同的SQL?还是在某些情况下会生成更有效的SQL?还是更糟糕的SQL?

Django annotations is great for average, min/max, etc. It also does Count. So does that generate the same SQL as if I used the older .count() on the queryset? Or does it generate more efficient SQL in some cases? Or worse SQL?

很抱歉,需要澄清的是,我的意思是将count()操作与诸如id为PK的aggregate(Count('id'))之类的东西进行比较

Sorry, to clarify, I meant to compare the count() operation against something like aggregate(Count('id')) where id is the PK of the table.

因此,我相信Brian的回答正确。简而言之,count()只是aggregate()的特例。

So with that, I believe Brian has the correct answer. In short, count() is simply a special case of aggregate().

推荐答案

调用查询集的 .count()方法最终会调用 Count()

Calling the queryset's .count() method ultimately calls 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 添加到查询中。

Specifically: django.db.models.QuerySet.count() calls django.db.models.sql.Query.get_count(), which calls django.db.models.sql.Query.add_count_column(), which adds django.db.models.sql.aggregates.Count to the query.

两者之间的主要区别在于,当您直接使用 Count 时,您要指定要计数的字段,而在调用 .count()在查询集上,这将导致 SELECT COUNT(*)... (除非您同时请使用distinct(),或者在select子句中限制字段时,这种情况会更复杂)。

The main difference between the two is that when you use Count directly, you specify the fields you want to count, whereas when you call .count() on the queryset, this will result in SELECT COUNT(*)... (except when you also use distinct() or when you limit the fields in the select clause, in which case it's more complicated).

这篇关于在Django中,无论如何,aggregate(Count())比.count()更快还是更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆