在Django 1.6和更早版本中,无法避免多余的查询。该
prefetch_related调用有效地缓存了
a.photoset.all()查询集中每个专辑的搜索结果。但是,这
a.photoset.filter(format=1)是一个不同的查询集,因此你将为每个专辑生成一个额外的查询。
这在
prefetch_related文档中进行了解释 。在
filter(format=1)相当于
filter(spicy=True)。
请注意,你可以改为使用python过滤照片来减少数量或查询:
someAlbums = PhotoAlbum.objects.filter(author="Davey Jones").prefetch_related("photo_set")for a in someAlbums: somePhotos = [p for p in a.photo_set.all() if p.format == 1]在Django 1.7中,有一个
Prefetch()对象可让你控制的行为
prefetch_related。
from django.db.models import PrefetchsomeAlbums = PhotoAlbum.objects.filter(author="Davey Jones").prefetch_related( Prefetch( "photo_set", queryset=Photo.objects.filter(format=1), to_attr="some_photos" ))for a in someAlbums: somePhotos = a.some_photos
有关如何使用该Prefetch对象的更多示例,请参阅prefetch_related文档。



