Reputation: 13860
I have three models:
class Model_1(models.Model):
...
class Model_2(models.Model):
m1 = models.ManyToManyField(Model_1,...
...
class Model_3(models.Model):
m2 = models.ManyToManyField(Model_2,...
...
and I get object of Model_1:
object = Model_1.objects.get(id=my_id)
How to get related Model_3 from object?
Upvotes: 0
Views: 204
Reputation: 9190
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
Upvotes: 0
Reputation: 6612
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
Upvotes: 0
Reputation: 53316
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.
Upvotes: 0
Reputation: 99620
If you are ok with 2 queries,
m2_objects = objects.model_2_set.all()
m3_objects = Model_3.objects.filter(m2__in=m2_objects)
Upvotes: 1