3

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?

Snipper03
  • 1,484
  • 4
  • 15
  • 29
  • Related: https://stackoverflow.com/questions/9622047/django-accessing-foreignkey-model-objects, https://stackoverflow.com/questions/2233883/get-all-related-django-model-objects?rq=1 – mic Jul 24 '19 at 18:37

1 Answers1

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
  • 5,450
  • 1
  • 33
  • 44
  • Thanks, @aliva for a quick answer. Then how about a reverse case: list_b=B.objects.filter() How can get the A object list which is related with B? – Snipper03 Jun 22 '18 at 10:15
  • I tried it, but I am getting this error: "Cannot resolve keyword 'b' into field." because A object doesn't have a field named 'b' – Snipper03 Jun 22 '18 at 10:32
  • sorry it's based on my note about changing related_name to 'b', – aliva Jun 22 '18 at 10:37
  • B object has A object as a foreign key. So your code should be b=model.ForeignKey(A, related_name='b') right? Then A.objects.filter(b__in=b_list) will work? – Snipper03 Jun 22 '18 at 10:39
  • I think you should check this link to see how django related relations work https://docs.djangoproject.com/en/2.0/topics/db/queries/#backwards-related-objects – aliva Jun 22 '18 at 12:13