【问题标题】:Django m2m relation of the model with itself with extra attributes模型与自身的 Django m2m 关系具有额外的属性
【发布时间】:2015-05-29 18:05:34
【问题描述】:

我试图创建一个具有多对多自我关系的模型,我把它放在我的代码中:

class Person(models.Model):
    name = models.CharField(max_length=50)
    shape_clm = models.ManyToManyField("self", through='Friend',                                                                symmetrical=False) 

    def __str__(self):
        return self.name


class Friend(models.Model):
    pers_one = models.ForeignKey(Person)
    pers_two = models.ForeignKey(Person)
    type = models.CharField(max_length=150)

但是当我尝试将模型迁移到数据库时,出现以下错误:

Friend.pers_one: reverse accessor for Friend.pers_one clashes with reverse accessor for Friend.pers_two

我使用 Postgres 作为数据库服务器,如何建立这种 m2m 关系?

【问题讨论】:

    标签: django django-models many-to-many


    【解决方案1】:

    您需要添加 related_name 关键字参数,否则 ORM 无法判断您将如何引用其中任何一个字段。

    class Friend(models.Model):
        pers_one = models.ForeignKey(Person, related_name='pers_ones')
        pers_two = models.ForeignKey(Person, related_name='pers_twos')
    

    【讨论】:

      【解决方案2】:

      Friend ModelClass 中将related_name 参数添加到您的ForeignKeys:

      class Friend(models.Model):
          pers_one = models.ForeignKey(Person, related_name="friends_one")
          pers_two = models.ForeignKey(Person, related_name="friends_two")
          type = models.CharField(max_length=150)
      

      有关related_name 的更多信息,请查看docs

      【讨论】:

      • 我在我的字段中添加了一个related_name,但错误仍然存​​在。最后,我将字段 unique_together('pers_one', 'pers_two') 添加到 Friend 类中的 Meta 类中,它运行良好,无论如何感谢您的回答
      猜你喜欢
      • 1970-01-01
      • 2015-06-03
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多