开发者

How to SelectMany using a Django QuerySet?

Suppose I have two models, A and B, 开发者_如何学Gowhere an A can have multiple Bs 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜