Home > Software engineering >  Does it matter in which order you use prefetch_related and filter in Django?
Does it matter in which order you use prefetch_related and filter in Django?

Time:12-21

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?

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

Thanks in advance.

CodePudding user response:

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).

  • Related