现有两个表:患者(patient)表和样本(sample)表,其关系为一对多。首先向患者表添加患者的基本信息,接下来向样本表中添加样本信息。此时,在样本信息中需要选择患者表中已经有的患者信息(比如患者姓名),这里需要用form表单关联上令一张表。
做法:
class PatientForm(forms.Form):
patient_id = forms.CharField()
patient_name = forms.CharField()
patient_age = forms.IntegerField()
class SampleForm(forms.Form):
sample_id = forms.CharField()
patient_id = forms.CharField(widget=forms.Select(choices=Patient.objects.all().values_list('patient_id','patient_name')))
这样form表单渲染到前端之后将病人表中的病人姓名显示出来,并且单选框中的value值为病人的id。
后端再拿到前端传到的值后
sample_post = SampleForm(request.POST)
if sample_post.is_valid():
patient_object=Patient.objects.filter(patient_id=sample_post.cleaned_data['patient_id'])
sample_post.cleaned_data['pat