django - 具有一对一字段的模型在保存后不保存(提交=假)
问题描述
我有代码崩溃,但其他字段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,但存在同样的问题。问题出在哪里?
谢谢
解决方案
您的代码运行良好。如果您仍然需要帮助,请展示您使用 Django shell 的尝试。
推荐阅读
- ios - WKWebView loadFileURL:allowingReadAccessToURL: 不允许访问文件或临时文件中的捆绑包
- javascript - React Reusable Button Component - 如何正确传递背景颜色道具?
- css - 动态 CSS 网格小列,先有一个大列
- java - LLVM IR 与 JAVA-API
- windows - 默认安装后,Windows 2016 Server 上的 SSMS.exe 在哪里?
- python - 迭代字符串列表以提取子字符串
- python - 训练和验证损失为零
- angularjs - 在 AngularJS 1.4.x 中将属性从父指令转发到子元素
- itext7 - iText7 数字签名图像对齐
- java - Spring Boot 调度程序中的 Java 邮件发送器