5π
β
B.objects.filter(a__in=a_list)
note that you can filter on related objects like this (instead if executing two queries do it in one)
for example if your a_list is a query like this:
a_list = A.objects.filter(field=2)
you can filter B like this:
B.objects.filter(a__field=2)
which is more readable and also django can optimize it too)
Update: you can query reversed relations the same way
A.objects.filter(b__in=b_list)
A.objects.filter(b__field=2)
note that itβs better to change your code to
a = model.ForeignKey(A, related_name='b')
b
is the name of the field in reveres relations so an_a_instance.b.all()
returns all instances of b
which are pointing at given a_instance
π€aliva
Source:stackexchange.com