2014-01-30 82 views
0

我有一個叫Person的模型,一個人可能有或沒有幾個關係;配偶,孩子,父母。如果人員有配偶,但配偶不是數據庫中的人員,我希望能夠將配偶作爲一個字符串值而不是另一個人。正因爲如此我想我需要在M2M關係中指定的through模型:Django ORM配偶,子女,父母關係

class Person(models.Model): 
    spouse = models.ManyToManyField('self', through='Relationship') 
    children = models.ManyToManyField('self', through='Relationship') 
    parents = models.ManyToManyField('self', through='Relationship') 

class Relationship(models.Model): 
    personA = models.ForeignKey(Person) 
    personB = models.ForeignKey(Person, blank=True, null=True) 
    person_name = models.TextField(default='', blank=True) 
    relationship = models.CharField(choices=(('s', 'spouse'), 
              ('c', 'child'), 
              ('p', 'parent')), 
            default='s') 

當我嘗試運行./manage.py遷移我收到以下錯誤信息顯示出來:

 
CommandError: One or more models did not validate: 
myapp.person: Many-to-many fields with intermediate tables cannot be symmetrical. 
myapp.person: Many-to-many fields with intermediate tables cannot be symmetrical. 
myapp.person: The model Person has two manually-defined m2m relations through the model Relationship, which is not permitted. Please consider using an extra field on your intermediary model instead. 
myapp.person: Many-to-many fields with intermediate tables cannot be symmetrical. 
myapp.person: The model Person has two manually-defined m2m relations through the model Relationship, which is not permitted. Please consider using an extra field on your intermediary model instead. 
myapp.relationship: Accessor for field 'personA' clashes with related field 'Person.relationship_set'. Add a related_name argument to the definition for 'personA'. 
myapp.relationship: Accessor for field 'personB' clashes with related field 'Person.relationship_set'. Add a related_name argument to the definition for 'personB'. 

顯然我做錯了。

如何指定同一模型與關聯的額外數據之間的關係?

或者,您還可以如何構建這些模型以跟蹤相同的數據?

+0

爲什麼不把它們作爲用戶存儲? –

+0

他們不是用戶。他們是作者,插圖畫家等,也與書籍,電影等有關。 – chadgh

+0

對不起,爲什麼不把它們作爲[插入你在這裏使用的任何模型]而不是一個字符串? –

回答

0

Error creating several recursive m2m relationships看起來像一個相關的問題。我意識到我可以通過從Person模型中刪除parents,children,spouse字段並在Relationship模型上將related_name設置爲relationships來獲得相同的效果。

class Person(models.Model): 
    [ other fields ] 

class Relationship(models.Model): 
    personA = models.ForeignKey(Person, related_name='relationships') 
    personB = models.ForeignKey(Person, blank=True, null=True) 
    person_name = models.TextField(default='', blank=True) 
    relationship = models.CharField(choices=(('s', 'spouse'), 
              ('c', 'child'), 
              ('p', 'parent')), 
            default='s') 

我還沒有測試過它,但它確實並且不會再拋出錯誤消息。這似乎也更清潔。

我想我可以創建在Person模型的一些特性給我訪問說Person.spouse返回所有Person.relationships其中relationship == 's'

+0

這是行不通的。我曾經在類似的情況下做過類似的事情,而且這個解決方案很好。 – chadgh