Search code examples
pythondjangoeager-loading

django eager loading one-to-many relationships


Simple question, I've searched and can't figure this out...

How do I setup eager loading in 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)

I now want to retrieve all albums and all photos, with a single call to the DB. albums = Album.objects.filter(user=request.user).all()

I've looked at select_related() and prefetch_related() but these looks to be for the reverse (getting the album object at the same time as the photo objects, when querying against the photo object)


Solution

  • Ok, the key here was albums = Album.objects.filter(user=request.user).prefetch_related('photo_set')

    specifically, prefetch_related('FOO_set') where 'FOO' is the related object name

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