Django: How to get related objects of a queryset?

0

Issue

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.

Solution

You can use __in:

A.objects.filter(b__in=bs)

or you can avoid creating the bs queryset at all, and follow the relation directly in your query:

A.objects.filter(b__<bcondition>=<bvalue>)

For example, if the filter used to create bs was:

bs = B.objects.filter(name="Banana")

Then you could filter the A objects using:

A.objects.filter(b__name="Banana")

Bear in mind that there are a number of different ways you can filter, and that the filter functionality is quite extensive, so it is worth reviewing the filter documentation

Answered By – Daniel Roseman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More