Why does django's prefetch_related() only work with all() and not filter()?

问题:

suppose I have this model:假设我有这个模型:

class PhotoAlbum(models.Model):
    title = models.CharField(max_length=128)
    author = models.CharField(max_length=128)

class Photo(models.Model):
    album = models.ForeignKey('PhotoAlbum')
    format = models.IntegerField()

Now if I want to look at a subset of photos in a subset of albums efficiently.现在,如果我想有效地查看相册子集中的照片子集。 I do it something like this:我这样做:

someAlbums = PhotoAlbum.objects.filter(author="Davey Jones").prefetch_related("photo_set")
for a in someAlbums:
    somePhotos = a.photo_set.all()

This does only two queries, which is what I expect (one to get the albums, and then one like `SELECT * IN photos WHERE photoalbum_id IN ().这仅执行两个查询,这正是我所期望的(一个是获取相册,另一个是像`SELECT * IN photos WHERE photoalbum_id IN ()。

Everything is great.一切都很棒。

But if I do this:但如果我这样做:

someAlbums = PhotoAlbum.objects.filter(author="Davey Jones").prefetch_related("photo_set")
for a in someAlbums:
    somePhotos = a.photo_set.filter(format=1)

Then it does a ton of queries with WHERE format = 1 !然后它使用WHERE format = 1进行大量查询! Am I doing something wrong or is django not smart enough to realise it has already fetched all the photos and can filter them in python?我做错了什么还是django不够聪明,无法意识到它已经获取了所有照片并且可以在python中过滤它们? I swear I read somewhere in the documentation that it is supposed to do that...我发誓我在文档中的某处读到它应该这样做......


解决方案:

参考: https://stackoom.com/en/question/sR6v
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章