[Answer]-How to get related object?

1👍

If you are ok with 2 queries,

m2_objects = objects.model_2_set.all()
m3_objects = Model_3.objects.filter(m2__in=m2_objects)

0👍

ManyToMany gives you a set not one object.
You can get objects of Model_3 like this

>>> object = Model_1.objects.get(id=my_id)
>>> for o2 in object.model_2_set.all():
>>>     for o3 in o2.model_3_set.all():
>>>         print o3  # o3 is one of Model_3 object

Change model_2_set to whatever related_name you have provided.

👤Rohan

0👍

Here is a solution with prefetch_related that does only 3 queries.

object = Model_1.objects.get(id=my_id) # 1 query
m2_set = object.model2_set.prefetch_related('model3_set') # 2 queries for model 2 and 3
for o3 in chain(*(m2.m3_set.all() for m2 in m2_set)): # chaning o3 sets (no query)
    print o3 # probably no query 

source:
prefetch_related: https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related
chain: http://docs.python.org/release/2.6.5/library/itertools.html#itertools.chain

0👍

Model_3.objects.filter(m2__m1=object)

It’s not intuitive, but an __exact filter matches if the value is among the set of related objects.

Edit: here’s the shell output, for kicks.

>>> from myapp.models import *
>>> m1 = Model_1.objects.create(name='it')
>>> m2 = Model_2.objects.create()
>>> m3 = Model_3.objects.create()
>>> 
>>> m1.model_2_set.add(m2)
>>> m2.model_3_set.add(m3)
>>> Model_3.objects.filter(m2__m1=m1).count()
1

Leave a comment