>>> queryset = Entry.objects.all() >>> print([p.headline for p in queryset]) # Evaluate the query set. >>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
注意! 不会cache的情况:
Specifically, this means that limiting the queryset using an array slice or an index will not populate the cache.
意思就是说queryset[5]和queryset[:5]是不会生成cache的. 还有exists()和iterator()这样的也不会生成cache.
举个栗子:
1 2 3 4 5 6 7 8
>>> queryset = Entry.objects.all() >>> print queryset[5] # Queries the database >>> print queryset[5] # Queries the database again >>> queryset = Entry.objects.all() >>> [entry for entry in queryset] # Queries the database >>> print queryset[5] # Uses cache >>> print queryset[5] # Uses cache
最近发现
values
和
values_list
这两个方法也会重新查询数据库, 不知道是为什么.
TODO: 有空看一下 具体的实现原理.
研究的结果:
当调用values或values_list的时候, 会生成一个新的queryset with no cache.
也就是说, 除了上边说到的七种会产生cache的情况, 其他都会重新去数据库拿数据.