Django: How to get related objects of a queryset?

Viewed 20700

Assume I have two models:

A:
    pass

B:
    a = foreign_key(A)

Now, I have a query set

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

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

Is there a way to do so? I think in sql, a simple join will do, I don't know if django support this.

2 Answers

Extending Daniel's solution, using __in might return duplicate records if using a related model.

For example:

A.objects.filter(b__in=bs).count() could be more than A.objects.all().count()

For me, using distinct() worked as mentioned in this SO answer

A.objects.filter(b__in=bs).distinct()

Related