Django QuerySet 有多懒?

How lazy are Django QuerySets?

下面的代码会查询数据库两次吗?当然一旦开始 for 循环,但它是否使用 len() 查询数据库?我问这个是因为我知道 Django count() 函数查询数据库。

events = Events.objects.all()   

for event in events:         #First Query
    print(event.name)

length = len(events)         #Second Query?

它只会访问数据库一次,因为 documented

In a newly created QuerySet, the cache is empty. The first time a QuerySet is evaluated – and, hence, a database query happens – Django saves the query results in the QuerySet’s cache and returns the results that have been explicitly requested (e.g., the next element, if the QuerySet is being iterated over). Subsequent evaluations of the QuerySet reuse the cached results.