views:

45

answers:

1

Suppose I have two models, A and B, where 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)

+2  A: 

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)
Daniel Roseman
A is a class encapsulating the model. filter() call on objects returns a query set that you are looking for. If you need one item use .get() but if multiple items will be found it will raise A.MultipleObjectsReturned error.
Evgeny