我有三种模式:
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,...
...
我得到了Model_1的对象:
object = Model_1.objects.get(id=my_id)
如何从对象获取相关的Model_3?
答案 0 :(得分:1)
如果您对2个查询没问题,
m2_objects = objects.model_2_set.all()
m3_objects = Model_3.objects.filter(m2__in=m2_objects)
答案 1 :(得分:0)
ManyToMany
为您提供一个不是一个对象的集合。
你可以像这样获得Model_3
的对象
>>> 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
将model_2_set
更改为您提供的related_name
。
答案 2 :(得分:0)
这是一个prefetch_related只能执行3次查询的解决方案。
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
源: prefetch_related:https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related 链:http://docs.python.org/release/2.6.5/library/itertools.html#itertools.chain
答案 3 :(得分:0)
Model_3.objects.filter(m2__m1=object)
这不直观,但如果值在相关对象集合中,则__exact过滤器匹配。
编辑:这是shell输出,用于踢。
>>> 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