class Operation(models.Model):
Operation_Name = models.CharField(max_length = 100)
class Doctor(models.Model):
Name = models.CharField(max_length = 100)
Related_Operations = models.ManyToManyField(Operation,through='Unique_Operation_Doctor_Patient_Relation')
def __str__(self):
return self.Name
class Unique_Operation_Doctor_Patient_Relation(models.Model):
# the doctor and the operation
Concerned_Doctor = models.ForeignKey(Doctor)
Concerned_Operation = models.ForeignKey(Operation)
# Attributes of the operation
Date = models.DateTimeField(db_index = True)
Tooth_Surface = models.IntegerField(db_index = True)
Amount = models.IntegerField(db_index = True)
Concerned_Patient = models.ForeignKey(Patient,db_index = True)
Idtag = models.AutoField(primary_key = True,default = 200000,db_index = True)
以下是两个模型Doctor和Operation之间通过中间模型建立的多对多关系。我还添加了一个外键字段,将其链接到患者,以便我可以访问患者记录。我为中间模型创建了一个表单。在这个模型中,我保存了医生和患者的关系,但我只在视图功能中添加了与患者的关系。
class Try_Form(forms.ModelForm):
class Meta:
model = Unique_Operation_Doctor_Patient_Relation
fields = ['Concerned_Doctor','Concerned_Operation','Concerned_Patient','Date','Tooth_Surface','Amount',]
help_texts ={
'Date': ' (YYYY-MM-DD)',
}
New_Operation_Name = forms.CharField(max_length = 100)
New_Doctor_Name = forms.CharField(max_length = 100)
field_order = ['Date','Tooth_Surface','Amount','Concerned_Operation','New_Operation_Name','Concerned_Doctor','New_Doctor_Name','Concerned_Patient']
def __init__(self,*args,**kwargs):
super(Try_Form,self).__init__(*args,**kwargs)
self.fields['Concerned_Doctor'].required = False
self.fields['Concerned_Operation'].required = False
self.fields['Concerned_Patient'].required = False
def clean(self):
# The connected doctors. Creating new Doctors if they don't exist and connecting them. The same for operations.
Existing_Operation_Connection = self.cleaned_data.get('Concerned_Operation')
New_Operation_Connection = self.cleaned_data.get('New_Operation_Name')
if Existing_Operation_Connection and not New_Operation_Connection:
self.Concerned_Operation = Existing_Operation_Connection
elif not Existing_Operation_Connection and New_Operation_Connection:
Possible_New_Operation,create = Operation.objects.get_or_create(Operation_Name = New_Operation_Connection)
if not create:
self.Concerned_Operation = Possible_New_Operation
else:
self.Concerned_Operation = Possible_New_Operation
else:
raise ValidationError("Please do not add a new operation and select an existing operation in the same form.")
Existing_Doctor_Connection = self.cleaned_data.get('Concerned_Doctor')
New_Doctor_Connection = self.cleaned_data.get('New_Doctor_Name')
if Existing_Doctor_Connection and not New_Doctor_Connection:
self.Concerned_Doctor = Existing_Doctor_Connection
elif not Existing_Doctor_Connection and New_Doctor_Connection:
Possible_New_Doctor,create = Doctor.objects.get_or_create(Name = New_Doctor_Connection)
if not create:
self.Concerned_Doctor = Possible_New_Doctor
else:
self.Concerned_Doctor = Possible_New_Doctor
else:
raise ValidationError("Please do not add a new doctor and select an existing doctor in the same form.")
return super(Try_Form,self).clean()
视图功能如下
def patient_tryform(request, pk):
if request.method == "POST":
form = Try_Form(request.POST)
if form.is_valid():
new_operation = form.save(commit = False)
connected_patient = Patient.objects.get(Patient_Id = pk)
new_operation.Concerned_Patient = connected_patient
new_operation.save()
return redirect('patient_treatmentrecord',pk = pk)
else:
form = Try_Form()
return render(request,'patient/patient_addoperation.html',{'form':form})
我得到的错误是line => new_operation.save()
IntegrityError => NOT NULL约束失败: patient_unique_operation_doctor_patient_relation.Concerned_Doctor_id。虽然我检查了python shell并且使用唯一的主键创建了医生。