[Django]-How to use prefetch_related across mutliple one-to-many relations in Django?

3👍

Complementing @themanatuf answer which was missing the prefetching of related Page models. Query code below will prefetch all Library models with their related Books and Pages, but restricting to Book genre=’fantasy’:

pf_queryset = models.Book.objects.filter(genre="fantasy").prefetch_related("page_set")
pf = Prefetch("book_set", queryset=pf_queryset)
models.Library.objects.prefetch_related(pf).all()

2👍

You’ll want to follow the instructions here:

https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-objects

Basically you’ll do something like this

books_query = Books.objects.filter(genre="fantasy")
pf = Prefetch("book_set", queryset=books_query)
Library.objects.prefetch_related(pf).get().book_set.all()

Leave a comment