2017-09-25 48 views
1

一個字段的值我有以下型號。插入一個在Django的

class PatientInfo(models.Model): 
    lastname = models.CharField('Last Name', max_length=200) 
    firstname = models.CharField('First Name',max_length=200) 
    middlename = models.CharField('Middle Name',max_length=200) 
    ... 
    def get_absolute_url(self): 
     return reverse('patient:medical-add', kwargs={'pk': self.pk}) 


class MedicalHistory(models.Model): 
    patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True,) 
    ... 

,並在提交PatientInfo形成就會去另一種形式提供MedicalHistory詳細信息。我可以看到我PatientInfo數據以及MedicalHistory數據,但不能相互鏈接。以下是我的MedicalCreateView處理我的MedicalHistory表單。

class MedicalCreateView(CreateView): 

    template_name = 'patient/medical_create.html' 
    model = MedicalHistory 
    form_class = MedicalForm 

    def post(self, request, pk): 
     form = self.form_class(request.POST) 


     if form.is_valid(): 
      patiente = form.save(commit=False) 
      physician_name = form.cleaned_data['physician_name'] # do not delete 
      patient = PatientInfo.objects.all(id=self.kwargs['pk']) 

      MedicalHistory.patient = self.kwargs['pk'] 


      patiente.save() 
      messages.success(request, "%s is added to patient list" % physician_name) 

      return redirect('index') 
     else: 
      print(form.errors) 

這是我如何使用PatientInfo.pk

MedicalHistory.patient = self.kwargs['pk'] 

回答

1

如果您正在使用OneToOneField和要鏈接到MedicalHistory自動PatientInfo您需要使用signals設置MedicalHistory.patient場。

class MedicalHistory(models.Model): 
    patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True,) 
    . . . . . 

@receiver(post_save, sender=PatientInfo) 
def create_medical_history(sender, instance, created, **kwargs): 
    if created: 
     MedicalHistory.objects.create(patient=instance) 

@receiver(post_save, sender=PatientInfo) 
def save_medical_history(sender, instance, **kwargs): 
    instance.medicalhistory.save() 

查看

class MedicalCreateView(CreateView): 

    template_name = 'patient/medical_create.html' 
    model = MedicalHistory 
    form_class = MedicalForm 
    success_url = '/' 
+0

我要刪除我的form.is_valid形式和使用返回重定向( '索引')呢?我應該如何在我的表單中調用created_medical history和save_medical_history。感謝您的答覆。 –

+0

先提交拋出錯誤就是這樣,唯一約束失敗:patient_medicalhistory.patient_id。然後當我刷新時,它會繼續到我的醫學歷史形式。當我填寫表格並提交它再次顯示了相同的輸入兩個記錄,PatientInfo和MedicalHistory之間仍然沒有聯繫。 –

+0

創建OneToOne場後,您需要格式化數據庫,以便只有1匹配。 –