【发布时间】:2016-11-21 18:40:48
【问题描述】:
我无法正确使用它,也无法在文档中找到它,但是在向 ManyToManyField 添加新对象时,我该如何添加到中间“通过”模型?
请注意,它是一种递归关系,但我使用了ManyToMany,因为我不确定OneToOne 是否支持“通过”模型(文档未指定)
无论(这是由于混淆 ManyToManyField 是 SQL 关系数据库中输出表中的实际字段)curr_partner 字段如何,都将使用Person_Person,向其添加诸如父/子关系之类的对象(Person 中没有字段)
(我意识到我的模型存在一些上下文/理论缺陷,但现在让我们抽象一下)
例如
模型.py:
class Person(models.Model):
objectid = models.AutoField(primary_key=True)
name = models.CharField()
curr_partner = models.ManyToManyField(
self,
on_delete = models.CASCADE,
through = Person_Person, #This lets you define the model that will act as an intermadiary
symmetrical = False, #This needs to be set with recursive relationships
)
class Person_Person(models.Model):
person_1 = models.ForeignKey(Person, ondelete=models.CASCADE)
person_2 = models.ForeignKey(Person, ondelete=models.CASCADE)
relation = models.ChoiceField(
('P', 'Parent'),
('C', 'Child'),
('E', 'Engaged'),
('W', 'Widow'),
)
查询:
#Adding a married couple
father = Person(name = "John")
mother = Person(name = "Anna")
father.curr_partner.add( mother , through.relation = "Engaged") #???
#Adding a 'Child' relation
child = Person(name = "Billy")
#This makes sense??
p1 = Person_Person(person1 = father, person2 = child, relation = "Child")
p2 = Person_Person(person1 = mother, person2 = child, relation = "Child")
【问题讨论】:
标签: python django django-models many-to-many