Django: Does prefetch_related() follow reverse relationship lookup?

Tianissimo picture Tianissimo · Feb 7, 2012 · Viewed 30.4k times · Source

I've tried prefetch_related() in django 1.4 from trunk and can't make it to prefetch reverse lookup.

My simplified models (each book has many prices):

class Book(models.Model):
    # some fields

class Price(models.Model):
    book = models.ForeignKey(Book)

My view's query:

books = Book.objects.prefetch_related('price')

Then, I got the AttributeError message:

AttributeError: Cannot find 'price' on Book object, 'price' is an invalid parameter to prefetch_related()

How to make it work? Thanks.

Answer

Jan Pöschko picture Jan Pöschko · Feb 7, 2012

Define a related name:

class Price(models.Model):
    book = models.ForeignKey(Book, related_name='prices')

and then use it:

books = Book.objects.prefetch_related('prices')