17

Let's say I have following models

class Foo(models.Model):
    ...

class Prop(models.Model):
    ...

class Bar(models.Model):
    foo: models.ForeignKey(Foo, related_name='bars', ...)
    prop: models.ForeignKey(Prop, ...)

Now I want to make the following query.

foos = Foo.objects.prefetch_related('bars__prop').all()

Does the above query makes 3 Database calls or only 2 (select_related for prop from bar), given that only one prop is associated with bar

If it takes 3 calls then, is there a way to make it 2 calls by using selected_related for bar -> prop

1

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)
    

1 Comment

I don't believe that the prefetch_related_objects() call is needed if we haven't retrieved the Foo objects before the prefetch_related(Prefetch('bars'...)) filter was attached to the QuerySet. I ran your validation statements (very cool!) w/o it and it showed everything properly in the cache.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.