[Django]-Django – joining two many-to-one relationships

2👍

Have you tried prefetch related? From docs:

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. 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.

prefetch_related, on the other hand, does a separate lookup for each
relationship, and does the ‘joining’ in Python. This allows it to
prefetch many-to-many and many-to-one objects, which cannot be done
using select_related, in addition to the foreign key and one-to-one
relationships that are supported by select_related.
more here

also when your relationship is not directly defined in the Class you are prefetching from, you can use classname_set to spawn reverse relationship

something like this should work:

Vendors.objects.select_related('legal_entities')
               .prefetch_related('legal_entities__legalentitiesdetails_set')

1👍

You can’t do that with select_related, since that only works on forwards relations and the link between LegalEntities and LegalEntitiesDetails is a backwards relation. You’ll need to use prefetch_related, which can follow backwards relations but uses two queries to do so.

Leave a comment