对Django QuerySet计数vs len [英] Count vs len on a Django QuerySet

查看:171
本文介绍了对Django QuerySet计数vs len的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,由于我有一个QuerySet,我将要迭代并打印结果,计数对象的最佳选择是什么? len(qs)或qs.count()?

In Django, given that I have a QuerySet that I am going to iterate over and print the results of, what is the best option for counting the objects? len(qs) or qs.count()?

(另外,在同一个迭代中计数对象不是一个选项)

(Also given that counting the objects in the same iteration is not an option)

推荐答案

尽管 Django docs < a>建议使用计数而不是 len


注意:如果您想要做的是确定集合中的记录数,请勿在QuerySets上使用 len()。使用SQL的 SELECT COUNT(*)处理数据库级别的计数效率要高得多,Django提供了一个 count()方法正是这个原因。

Note: Don't use len() on QuerySets if all you want to do is determine the number of records in the set. It's much more efficient to handle a count at the database level, using SQL's SELECT COUNT(*), and Django provides a count() method for precisely this reason.

由于您正在迭代此查询集,结果将被缓存(除非您使用 iterator ),所以它将优先使用 len ,因为这可以避免再次触发数据库,​​也可能是检索不同数量的结果!)。如果您使用 iterator ,那么建议您在重复执行时(包括使用计数)包括一个计数变量。

Since you are iterating this QuerySet anyway, the result will be cached (unless you are using iterator), and so it will be preferable to use len, since this avoids hitting the the database again, and also the possibly of retrieving a different number of results!). If you are using iterator, then I would suggest including a counting variable as you iterate through (rather than using count) for the same reasons.

这篇关于对Django QuerySet计数vs len的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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