django can we select related a field on a prefetch related model?

This answer is correct with versions of Django prior to 1.7. It produces three queries: first, fetch the instance of A, then fetch its related instances of B and finally fetch the instances of C related to those of B fetched in the second query.

Before Django 1.7, this is the best you can do, even though the second query could, in theory, select all B objects together with the related C objects joined through the z ForeignKey.

Starting with Django 1.7, there's a more advanced django.db.models.Prefetch class which allows you to do just that. With Prefetch you can customize the queryset used to prefetch related objects like this:

foo = A.objects.prefetch_related(
    Prefetch('a', queryset=B.objects.select_related('z'))
).get(pk=1)

This results in only two queries (as opposed to three when using prefetch_related('a__z')) and lets the database take care of the second join, which should in theory result in slightly better performance.


You only need one prefetch_related call:

foo = A.objects.prefetch_related('a__z').get(pk=1)

This will prefetch both tables. In Django 1.7+ you can improve performance by using a Prefetch object, as in koniiiik's answer.

Tags:

Django