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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章