简体   繁体   中英

Django: How to get related objects of a queryset?

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.

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM