select_related with reverse foreign keys select_related with reverse foreign keys django django

select_related with reverse foreign keys


Yes, that is what prefetch_related() is for. It will require an additional query, but the idea is that it will get all of the related information at once, instead of once per Person.

In your case:

qs.select_related('position__report_to')  .prefetch_related('position__report_to__person_set')

should require two queries, regardless of the number of Persons in the original query set.

Compare this example from the documentation:

>>> Restaurant.objects.select_related('best_pizza')                      .prefetch_related('best_pizza__toppings')