通过模型使用 Django 查询

Django query using through model

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

如何通过 'x'

筛选来查询 a

创建字段时需要定义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 class。它必须定义两个外键字段回到 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