在django中插入一对一字段值

时间:2017-09-25 22:36:50

标签: django forms

我有以下型号。

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字段的方法
MedicalHistory.patient = self.kwargs['pk']

1 个答案:

答案 0 :(得分:1)

如果您使用a<b?b:a 并希望自动将OneToOneFieldMedicalHistory关联,则需要使用PatientInfo

signals

<强>视图

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()