[Fixed]-Django chaining prefetch_related and select_related

19👍

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.

1👍

You will have to use Prefetch class along with prefetch_related_objects

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

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

 print(foos[0]._prefetched_objects_cache)
 print(foos[0].bars.all()[0]._state.fields_cache)
    

Leave a comment