gpt4 book ai didi

python - 将对象添加到 ManyToManyField 时,Django 如何填充 'trough' 中间模型中的字段?

转载 作者:太空宇宙 更新时间:2023-11-03 15:56:28 25 4
gpt4 key购买 nike

我无法正确表达它,也无法在文档中找到它,但是在向 ManyToManyField 添加新对象时,如何将其添加到中间“通过”模型?

请注意,它是一种递归关系,但我使用了ManyToMany,因为我不确定OneToOne是否支持“通过”模型(文档没有指定它)

此外,无论 curr_partner 字段如何,都将使用 Person_Person,向其添加诸如 parent /子女关系之类的对象(在 Person 中没有字段) ) (这是由于混淆了 ManyToManyField 是 SQL 关系数据库中输出表中的实际字段)

(我意识到我的模型存在一些上下文/理论缺陷,但现在让我们抽象一下)

例如

模型.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")

最佳答案

您通过保存关系模型的实例来创建关系,就像您(几乎)对 child 所做的那样。你会有类似的东西

father = Person(name = "John")
mother = Person(name = "Anna")

marriage = Person_Person.objects.create(person1=father, person2=mother, relation="E")

p1 = Person_Person.objects.create(person1=father, person2=child, relation="C")
p2 = Person_Person.objects.create(person1 = mother, person2 = child, relation="C")

顺便说一句,您的 curr_partner 属性没有准确的名称,因为它实际上表示一个人的所有关系,而不仅仅是婚姻。也许您应该将其重命名为 relationshipskindred 并拥有一个属性来获取此人的伴侣:

@property
def curr_partner(self):
try:
return self.relationships.objects.get(relation='E')
except Person_Person.DoesNotExist:
# No marriage relationship
return

关于python - 将对象添加到 ManyToManyField 时,Django 如何填充 'trough' 中间模型中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40727200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com