我有 4 个表单,用户通过单击一个 Submit
按钮来提交。形式为:
人员表单
- 将保存到人员模型地址表单
- 将保存到地址模型电子邮件表单
- 将保存到电子邮件模型电话表单
- 将保存到电话型号。
因此,一个人
可以拥有多个地址
、电子邮件
和电话
号码。所以,我在 Person 模型中这样做了:
class Person(models.Model):
first_name = models.CharField(max_length=99)
middle_name = models.CharField(max_length=99, blank=True, null=True)
last_name = models.CharField(max_length=99, blank=True, null=True)
address = GenericRelation('Address')
phone = GenericRelation('Phone')
email = GenericRelation('Email')
我有这 3 行以及它们各自的模型字段:Address
、Phone
和 Email
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
现在,当我收到用户的表单时,如何在我的 View 中正确地将数据保存到这些模型中?这是我到目前为止所拥有的。
if request.method == 'POST':
if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \
and phone_form.is_valid():
address = address_form.save()
email = email_form.save()
phone = phone_form.save()
person = person_form.save(commit=False) #This person model has a generic foreign key relation with Address, Email and Phone
person.address = (address) #This is where I need help. Am I thinking right? Is this the right way to save?
最佳答案
需要在定义GFK的模型中设置内容对象,我修改了代码,
if request.method == 'POST':
if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \
and phone_form.is_valid():
person = person_form.save()
address = address_form.save(commit=False)
address.content_object = person
address.save()
email = email_form.save(commit=False)
email.content_object = person
email.save()
phone = phone_form.save(commit=False)
phone.content_object = person
phone.save()
但我有一个严重的疑问?为什么您在模型中使用通用外键?这些模型是否可以引用 Person 之外的任何其他模型。
关于python - 如何从我的 View 中设置 django 通用外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47628735/