Django查询集和生成器 [英] Django queryset and generator

查看:182
本文介绍了Django查询集和生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

突然之间,我想知道使用生成器迭代结果集的以下方式是否会对正常迭代产生任何正面或负面影响?

Just out of the blue I wonder if the following way of iterating through a result set using generator will cause any positive or negative impact against normal iteration?

例如。

def all_items_generator():
  for item in Item.objects.all():
    yield item

for item in all_items_generator():
  do_stuff_with_item(item)

反对:

for item in Item.objects.all():
  do_stuff_with_item(item)


推荐答案

前者会慢一些,因为它会创建一个包含所有内容的列表模型然后一次一个地产生它们,而后者将直接使用该列表。如果你想要一个生成器,那么你应该使用 QuerySet而不是.iterator()

The former will be slower, since it will create a list containing all the models and then yield them one at a time, whereas the latter will just use the list directly. If you want a generator then you should use QuerySet.iterator() instead.

这篇关于Django查询集和生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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