In Django, one can select_related and prefetch_related. The former expands the DB query by extra fields and is used when there is at most one result ("parent" relationship, for example item.owner), while the latter produces an extra DB query and is used when there are multiple expected results ("children" relationship, for example user.items).

The criterion on which to use seems very straightforward to me:

  1. select_related is "better", as it doesn't introduce extra queries, but it is limited to 1:1 and n:1 relationships.
  2. prefetch_related can do any preloading, but at the cost of extra queries, so one would use it when select_related cannot work.

Even the official documentation says:

However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

So, the criterion is as straightforward as it can be (unless I'm missing something). Further, Django has access to the whole DB definition via models, so it should be able to determine which relations are "parent" and which are "children".

My question is: why can't there be a single preload(...) method which would pick the ideal approach (equivalent to select_related for "parent" fields and prefetch_related for "children")? Am I missing something in how these are used or is there a deeper underlying problem preventing Django team from writing such a method?

New contributor
Vedran Šego is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

Vedran Šego is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.