2013-02-19 64 views
0

我需要存儲人與人之間的關係。所以,我有以下型號創建多個遞歸的m2m關係時出錯

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'. 

任何幫助,將不勝感激。

回答

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")