【发布时间】:2020-11-15 17:12:07
【问题描述】:
我的代码有问题,但patient_specification 的其他字段不会被保存。
代码没有报错,运行正常。
当我从 db 读取 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})
我也尝试将save(commit=false) 替换为PatientSpecification() 或patient_specification.patient = patient 替换为patient_specification.patient = Patient.objects.get(national_code=patient.national_code) 但没有成功,patiet_spacification 不保存普通字段。
我也尝试过使用 django shell,但存在同样的问题。
问题出在哪里?
谢谢
【问题讨论】:
标签: django database django-forms one-to-one