Django: How to get related query objects?

Suppose I have two models:

A:
    pass

B:
    a = foreign_key(A)

I now have a set of queries

bs = B.objects.filter(...)

I want to get all a from bs, which means every a referenced by b for which b is in bs.

Is there any way to do this? I think in sql, a simple connection will be, I don't know if django supports this.

+4
source share
1 answer

You can use __in:

A.objects.filter(b__in=bs)

or you can skip the bs query set at all and follow the direct query:

A.objects.filter(b__bcondition=bvalue)
+10
source

All Articles