In Django, one can
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
The criterion on which to use seems very straightforward to me:
select_relatedis "better", as it doesn't introduce extra queries, but it is limited to 1:1 and n:1 relationships.
prefetch_relatedcan do any preloading, but at the cost of extra queries, so one would use it when
Even the official documentation says:
However, to avoid the much larger result set that would result from joining across a ‘many’ relationship,
select_relatedis 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?