Django如何使用外键保存表单集?

时间:2018-12-13 10:47:37

标签: python django

我有两个由外键关联的雇员和孩子(婴儿)模型,例如 models.py

 class Enfant(models.Model) :
     id_emp = models.ForeignKey(Employee, on_delete=models.CASCADE)
     id_Enfant=models.IntegerField(blank=True,primary_key=True)

views.py

form = EmployeeForm(request.POST or None)
form_EnfantForm_formset =formset_factory(EnfantForm, formset=EnfantFormSet)
if request.method == 'POST'
        if form.is_valid() :
            #pdb.set_trace()
            new_employee=form.save()
            EnfantForm_formset0 = form_EnfantForm_formset.save(commit=False)
            EnfantForm_formset0.employee= new_employee
            EnfantForm_formset0.save()

我需要保存员工记录和婴儿记录

1 个答案:

答案 0 :(得分:0)

保存表单集将返回实例列表。您必须遍历此列表并分配字段:

instances = form_EnfantForm_formset.save(commit=False)
for instance in instances:
    instance.employee = new_employee
    instance.save()

来源:https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#saving-objects-in-the-formset