如何从我的视图中设置django通用外键?

时间:2017-12-04 07:50:18

标签: python django forms

我有4个用户通过点击一个Submit按钮提交的表单。表格是:

  1. Person Form - 将保存为人员模型
  2. Address Form - 将保存到地址模型
  3. Email Form - 将保存为电子邮件模型
  4. Phone Form - 将保存到手机型号。
  5. 因此,Person可以包含多个AddressesEmailsPhone个数字。所以,我在人物模型中做到了这一点:

    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行以及AddressPhoneEmail

    各自的模型字段
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    

    现在,当我从用户那里收到表单时,如何在我的视图中正确地将数据保存到这些模型?这就是我到目前为止所做的。

     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?
    

1 个答案:

答案 0 :(得分:1)

你需要在模型中设置内容对象,其中定义了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()

但我有一个严重怀疑?为什么你的模型中使用Generic Foreign Key?这些模型可以引用除Person之外的任何其他模型。