python – 与Django中相同模型的多对多关系 - 代码日志

python – 与Django中相同模型的多对多关系

给定以下两个关系的模型:

class Child(models.Model):
    name = models.CharField(max_length=80)

class Foo(models.Model):
    bar = models.ManyToManyField(Child)
    baz = models.ManyToManyField(Child)

这给出错误:

accounts.foo: Accessor for m2m field 'bar' clashes with related m2m field 'Child.foo_set'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Accessor for m2m field 'baz' clashes with related m2m field 'Child.foo_set'. Add a related_name argument to the definition for 'baz'.

精细;我不需要向后关系。 According to the Django docs for related_name(只有在外键可以看到),我可以设置related_name =“”,后退关系不会被创建:

class Child(models.Model):
    name = models.CharField(max_length=80)

class Foo(models.Model):
    bar = models.ManyToManyField(Child, related_name="+")
    baz = models.ManyToManyField(Child, related_name="+")

这不行:

accounts.foo: Accessor for m2m field 'bar' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Reverse query name for m2m field 'bar' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Accessor for m2m field 'baz' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'baz'.
accounts.foo: Reverse query name for m2m field 'baz' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'baz'.

我需要做什么才能避免产生反向关系?

我想你只需要给两个不同的相关的域名:

class Child(models.Model):
  name = models.CharField(max_length=80)

class Foo(models.Model):
  bar = models.ManyToManyField(Child, related_name="bar")
  baz = models.ManyToManyField(Child, related_name="baz")

如果您没有给出相关的名称,那么它尝试在Child模型上创建两次相同的访问器名称(foo_set)。如果您提供相同的相关名称,它将再次尝试创建相同的访问器两次,因此您需要提供唯一的相关名称。使用上面的代码来定义你的模型,然后给出一个Child实例c,你可以使用c.bar.all()和c.baz.all()来访问相关的Foo对象。

如果您不想要向后关系,请附加到每个(唯一)相关名称:

class Foo(models.Model):
  bar = models.ManyToManyField(Child, related_name="bar+")
  baz = models.ManyToManyField(Child, related_name="baz+")
http://stackoverflow.com/questions/13918968/multiple-many-to-many-relations-to-the-same-model-in-django

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 与Django中相同模型的多对多关系