[Fixed]-Django chaining prefetch_related and select_related


You can use the Prefetch class to specify the queryset that is used in prefetch_related() and this way combine it with select_related():

from django.db.models import Prefetch
bars = Bar.objects.select_related('prop')
foos = Foo.objects.prefetch_related(Prefetch('bars', queryset=bars)).all()

Note that this should be two queries, one for the Foo objects and one for getting the related Bar objects that are being joined in the same query with Prop.


You will have to use Prefetch class along with prefetch_related_objects

foos = Foo.objects.prefetch_related(Prefetch('bars', queryset=Bars.objects.all()))

You can validate wether the results are prefetched properly by using the below commands


Leave a comment