Suppose I have two models, A
and B
, 开发者_如何学Gowhere an A
can have multiple B
s related to it. Given a QuerySet of A
objects, how can I create a QuerySet containing all the B
objects related to all these A
objects?
For those who also happen to speak LINQ, I want something like this:
queryableOfA.SelectMany(a => a.Bs)
Even better would be an example of how to chain A -> B -> C, i.e. the following LINQ:
queryableOfA.SelectMany(a => a.Bs).SelectMany(b => b.Cs)
(returning a "queryset" of all C
objects related to all the A
objects through B
)
For a queryset of A objects, you can do an 'in' startup query:
B.objects.filter(a__in=MyQueryset)
If you want to find all C objects that are related through B to A, you need to follow the relationships via the double-underscore syntax. Something like:
C.objects.filter(b__a__in=MyAQueryset)
精彩评论