django 渴望加载一对多关系

django eager loading one-to-many relationships

简单的问题,我已经搜索过,但无法弄清楚...

如何在 Django 中设置预先加载?

class Album(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    title = models.CharField(max_length=255)
    description = models.CharField(max_length=255, blank=True)


class Photo(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    photo = models.ImageField(upload_to='photos/%Y/%m/%d/')


albums = Album.objects.filter(user=request.user).all()    
for album in albums:
    photos = album.photo_set.all()
    for photo in photos:
        print(photo.name)
        print(photo.photo)

我现在想通过一次调用数据库来检索所有相册和所有照片。 albums = Album.objects.filter(user=request.user).all()

我看过 select_related() and prefetch_related() 但这些看起来是相反的(在查询照片对象时,同时获取相册对象和照片对象)

好的,这里的关键是albums = Album.objects.filter(user=request.user).prefetch_related('photo_set')

具体来说,prefetch_related('FOO_set') 其中 'FOO' 是相关的对象名称

https://docs.djangoproject.com/en/2.1/topics/db/queries/#following-relationships-backward