一个简单的问题,我已经搜索过了,无法弄清楚...
如何在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)
我现在想通过一次调用DB来检索所有相册和所有照片。
albums = Album.objects.filter(user=request.user).all()
我看过select_related()和prefetch_related(),但它们看起来是相反的(在查询照片对象时,与照片对象同时获取相册对象)>
答案 0 :(得分:2)
好的,这里的密钥是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