[Answered ]-Django query optimization: find a list of objects based on a many-to-one to a many-to-many


Given an ObjectB, I need a set of
other ObjectBs that are the children
of the ObjectAs that are associated
with our ObjectB’s parent ObjectA.

If objb is the ObjectB you are given, you could do this as follows:

objects = ObjectB.objects.filter(object_a_association__object_a_rules=objb.object_a_association)

or alternatively,

objects = ObjectB.objects.filter(object_a_association__object_a_rules__objectb_set=objb)

See also Lookups that span relationships

Leave a comment