[英]Django: How to count a queryset and return a slice without hitting DB twice?
I have this part of the code in my API which recently has become a somewhat bottleneck: 我的API中有这部分代码,最近这已成为一个瓶颈:
total = results.count()
if request.GET.has_key('offset'):
offset = int(request.GET.get('offset').strip())
results = results.order_by('name')[100*offset:100*(offset+1)]
people = list(results)
Note that results
is the queryset of all the people and offset
is a param used for pagination. 请注意,
results
是所有人的查询集,而offset
是用于分页的参数。
Here I can see, when I print connection.queries
, that my database getting hit twice by .count()
and list(results)
. 在这里,我可以看到在打印
connection.queries
,数据库被.count()
和list(results)
击中两次。 The reason why .count()
has to be at the top because I need to the length of all the people (Not 100.) Is there a way to get around this? 之所以必须将
.count()
放在顶部是因为我需要所有人的长度(而不是100)。有没有办法解决这个问题?
Maybe something like this?: 也许是这样的:
allpeople = list(results.order_by('name'))
total = len(allpeople)
if request.GET.has_key('offset'):
offset = int(request.GET.get('offset').strip())
results = allpeople[100*offset:100*(offset+1)]
people = results
Keep in mind that with people = results
is going to fail if if request.GET....:
doesn't fire. 请记住,
if request.GET....:
不触发,则与people = results
将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.