Django通过模型查询

时间:2015-03-11 17:27:34

标签: django django-models

a = models.ManyToManyField('self', through = 'x')

如何通过“x”过滤来对a进行查询

1 个答案:

答案 0 :(得分:1)

创建字段时需要定义symmetrical=False。在Django 1.7中,如果您尝试定义,则会出现与此类似的错误:

CommandError: System check identified some issues:

ERRORS:
myapp.MyModel.a: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical. 

所以将字段更改为

a = models.ManyToManyField('self', through = 'x', symmetrical = False)

现在一切都取决于你的x课程。它必须将两个foreignKey字段定义回yourModel

class x(models.Model):
    from_a = models.ForeignKey(myClass, related_name = 'from_a')
    to_a = models.ForeignKey(myClass, related_name = 'to_a')
    comment = models.CharField(max_length = 255)

现在你不从x过滤,而是从FK创建的反向关系过滤,即:

myClass.objects.filter(from_a__comment='something')

或从实例角度来看:

my_instance.a.filter(from_a__comments='something')

有关该主题的精彩文章可在此处找到:Self-referencing many-to-many through