创建多个递归m2m关系时出错

时间:2013-02-19 01:38:19

标签: django django-models

我需要存储人与人之间的关系。所以我有以下模型

class Person(models.Model):
    name = models.CharField(max_length=255, blank=True)
    parents = models.ManyToManyField('self', through='PersonRelationship', symmetrical=False, blank=True, related_name="person_parents_set")
    friends = models.ManyToManyField('self', through='PersonRelationship', symmetrical=False, blank=True, related_name="person_friends_set") 

class PersonRelationship(models.Model):
    from_person = models.ForeignKey(Person, related_name="from_persons")
    to_person = models.ForeignKey(Person, related_name="to_persons")
    relation_start = models.DateField(blank=True)
    relation_end = models.DateField(blank=True)

当我尝试syncdb时,我收到此错误:

Error: One or more models did not validate:
films.person: The model Person has two manually-defined m2m relations through the model PersonRelationship, which is not permitted. Please consider using an extra field on your intermediary model instead.

我想我不能通过相同的模型建立两个m2m关系,所以我尝试为每种类型的关系创建一个模型,以避免重复我自己使用这样的抽象模型:

class PersonRelationship(models.Model):
    from_person = models.ForeignKey(Person, related_name="from_persons")
    to_person = models.ForeignKey(Person, related_name="to_persons")
    relation_start = models.DateField(blank=True)
    relation_end = models.DateField(blank=True)

    class Meta:
        abstract = True

class PersonParent(PersonRelationship):
    pass 

class PersonFriend(PersonRelationship):
    pass

我收到此错误,但我已经有了一个related_name:

films.personparent: Accessor for field 'from_person' clashes with related field     'Person.from_persons'. Add a related_name argument to the definition for 'from_person'.
films.personparent: Reverse query name for field 'from_person' clashes with related field    'Person.from_persons'. Add a related_name argument to the definition for 'from_person'.
films.personparent: Accessor for field 'from_person' clashes with related field 'Person.from_persons'. Add a related_name argument to the definition for 'from_person'.
films.personparent: Reverse query name for field 'from_person' clashes with related field 'Person.from_persons'. Add a related_name argument to the definition for 'from_person'.

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我刚刚找到解决方案,我发布的是以防有人从谷歌发现同样的问题。

阅读此链接[链接已更新至v1.9]:

https://docs.djangoproject.com/en/1.9/topics/db/models/#be-careful-with-related-name

所以我只是将相关名称改为:

from_person = models.ForeignKey(Person, related_name="%(app_label)s_%(class)s_from_persons")
to_person = models.ForeignKey(Person, related_name="%(app_label)s_%(class)s_to_persons")