首页 > 解决方案 > 具有一对一字段的模型在保存后不保存(提交=假)

问题描述

我有代码崩溃,但其他字段patient_specification不会被保存。
该代码没有显示任何错误并且正常运行。
当我patient_specification从 db 读取数据时,它们没有改变,除了患者字段之外的所有数据都是默认值。

# models.py

class Patient(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    national_code = models.BigIntegerField(default=1, unique=True)

class PatientSpecification(models.Model):
    patient = models.OneToOneField(Patient, on_delete=models.CASCADE, unique=True)
    weight = models.IntegerField(default=1)
    height = models.IntegerField(default=1)
    age = models.IntegerField(default=1)


# forms.py

class PatientForm(forms.ModelForm):

    class Meta:
        model = Patient
        fields = '__all__'

class PatientSpecificationForm(forms.ModelForm):
    
    class Meta:
        model = PatientSpecification
        exclude = ('patient', )


# views.py

def newPatient(request):
    if request.method == 'POST':
        form_p = PatientForm(request.POST)
        form_ps = PatientSpecificationForm(request.POST)
        if all([form_p.is_valid(), form_ps.is_valid()]):
            patient = form_p.save()
            patient_specification = form_ps.save(commit=False)
            patient_specification.patient = patient
            patient_specification.save()
            return render(request, 'sfl/home.html', {})
        else:
            print('not valid')
    else:
        form_p = PatientForm()
        form_ps = PatientSpecificationForm()
    return render(request, 'sfl/new_patient.html',
                      {'form_p': form_p, 'form_ps': form_ps})

我也尝试save(commit=false)PatientSpecification()patient_specification.patient = patient用替换patient_specification.patient = Patient.objects.get(national_code=patient.national_code)但没有成功,patiet_spacification不保存正常字段。
我也尝试过使用 django shell,但存在同样的问题。问题出在哪里?

谢谢

标签: djangodatabasedjango-formsone-to-one

解决方案


您的代码运行良好。如果您仍然需要帮助,请展示您使用 Django shell 的尝试。


推荐阅读