Assuming these as django model for the sake of simplcity:
class A():
a = manytomany(\'B\')
class B():
b = charfield()
z = foreignkey(\'C\')
class
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.