0

我有三个模型:

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?

4

4 回答 4

1

如果您对 2 个查询没问题,

m2_objects = objects.model_2_set.all()
m3_objects = Model_3.objects.filter(m2__in=m2_objects)
于 2012-09-28T11:42:32.957 回答
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
于 2012-09-28T21:37:58.193 回答
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

于 2012-09-28T11:34:34.240 回答
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

于 2012-09-28T12:41:29.130 回答