gpt4 book ai didi

django - 在 Django 查询集上使用 iterator()

转载 作者:行者123 更新时间:2023-12-03 20:21:46 24 4
gpt4 key购买 nike

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

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

例如

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

for book in allbooks:
do_something(book)

奇怪的是,它只返回了部分书籍列表。

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

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

知道为什么吗?

p.s.我确实查看了 Django 文档,但看不到查询集将如何被缓存在其他任何地方......

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

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.



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

checkin REPL 很容易。运行 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 - 在 Django 查询集上使用 iterator(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5058874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com