Django queryset上iterator()的用法 [英] usage of iterator() on django queryset

查看:452
本文介绍了Django queryset上iterator()的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一些奇怪的行为,需要检查我的理解。

I came across some strange behaviour recently, and need to check my understanding.

我在模型中使用了一个简单的过滤器,然后遍历结果。

I'm using a simple filter in the model and then iterating over the results.

例如

allbooks = Book.objects.filter(author='A.A. Milne')

for book in allbooks:
   do_something(book)

奇怪的是,它只返回部分书籍清单。

oddly, it was returning only a partial list of books.

但是,当使用相同的代码并使用iterator()时,这似乎很好用。

However, when using the same code and using iterator(), this seems to work well.

ie

for book in allbooks.iterator():
    do_something(book)

知道为什么吗?

ps我确实浏览了Django文档,但看不到如何将查询集缓存到其他地方...

p.s. I did look through the Django documentation, but can't see how the queryset would be cached already anywhere else...


iterator()
评估QuerySet(通过执行查询)并返回结果的迭代器。 QuerySet通常在内部缓存其结果,这样重复的求值不会导致其他查询。 iterator()将直接读取结果,而无需在QuerySet级别进行任何缓存。对于返回大量对象的QuerySet,这通常会导致更好的性能并显着减少内存

iterator() Evaluates the QuerySet (by performing the query) and returns an iterator over the results. A QuerySet typically caches its results internally so that repeated evaluations do not result in additional queries; iterator() will instead read results directly, without doing any caching at the QuerySet level. For a QuerySet which returns a large number of objects, this often results in better performance and a significant reduction in memory

请注意,使用 iterator() 在已经评估过的QuerySet上将迫使它再次评估,重复查询。

Note that using iterator() on a QuerySet which has already been evaluated will force it to evaluate again, repeating the query.


推荐答案


奇怪的是,它只返回了部分
图书清单。

oddly, it was returning only a partial list of books.

那不是查询集必须工作的方式。遍历queryset应该为您提供数据库返回的每条记录。调试代码。您会发现错误,否则请再次调试。

That's not how the queryset must work. Iterating over queryset should give you every record returned by your database. Debug your code. You'll find the error, otherwise debug it again.

检入REPL很容易。运行 manage.py shell

It's easy to check in the REPL. Run manage.py shell:

from app.models import Model
for o in Model.objects.filter(fieldname="foo"): print o

#Let's see DB query
from django.db import connection
print(connection.queries)

这篇关于Django queryset上iterator()的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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