Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does it matter in which order you use prefetch_related and filter in Django?

The title says it all.

Let’s take a look at this code for example:

objs = Model.objects.prefetch_related('model2').filter()
objs.first().model2_set.first().field

                  vs

objs = Model.objects.filter().prefetch_related('model2')
objs.first().model2_set.first().field

Question

When using prefetch_related() first, does Django fetch all the ManyToOne/ManyToMany relations without taking into consideration .filter() and after everything is fetched, the filter is applied?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

IMO, that doesn’t matter since there’s still one query executed at the end.

Thanks in advance.

>Solution :

It doesn’t matter where you specify prefetch_related as long as it’s before any records are fetched. Personally I put things like prefetch_related, select_related. and only at the end of the chain but that just feels more expressive to me from a code readability perspective.

But that is not true of all manager methods. Some methods do have different effects depending on their position in the chain, for example order_by can have positional significance when used with distinct (group by).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading