Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django getting foreign-key object list

I have model like this:

class A:
....


class B:
....
a = model.ForeignKey(A, related_name='a')
....

Let's assume there is an B object. I can get A object like this:

b = B()
a = b.a

Then what is the simplest way to get all B object related with A?

Additionally, I can get a list of A.

list_a = A.objects.filter()

Then what is the simplest way of getting a list of B which relates with A object in the list_a?

One more reverse case: I have a list of B:

list_b = B.objects.filter()

Then what is the simplest and optimized way to get the list of A object related to the B object in the list_b?

like image 238
Snipper03 Avatar asked Mar 06 '26 20:03

Snipper03


1 Answers

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

like image 82
aliva Avatar answered Mar 08 '26 10:03

aliva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!