34👍
✅
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
1👍
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()
- [Django]-Django south migration – Adding FULLTEXT indexes
- [Django]-How to add new languages into Django? My language "Uyghur" or "Uighur" is not supported in Django
- [Django]-How do I run tests against a Django data migration?
Source:stackexchange.com