我有一個叫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'.
顯然我做錯了。
如何指定同一模型與關聯的額外數據之間的關係?
或者,您還可以如何構建這些模型以跟蹤相同的數據?
爲什麼不把它們作爲用戶存儲? –
他們不是用戶。他們是作者,插圖畫家等,也與書籍,電影等有關。 – chadgh
對不起,爲什麼不把它們作爲[插入你在這裏使用的任何模型]而不是一個字符串? –