具有一对一字段的模型在保存后不保存(commit=False)

Model with a one to one field does not save after save(commit=False)

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

# 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})

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

谢谢

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