Carlos Fabiera
Carlos Fabiera

Reputation: 79

Insert One to One field value in django

I have the following models.

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,)
    ...

and upon submitting PatientInfo form it will go to another form which supply the MedicalHistory Details. I can see my PatientInfo data as well as MedicalHistory data but not linked to each other. Below is my MedicalCreateView which process my MedicalHistory form.

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)

This is how I set MedicalHistory.patient field using the PatientInfo.pk

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

Upvotes: 1

Views: 1906

Answers (1)

Astik Anand
Astik Anand

Reputation: 13057

If you are using OneToOneField and want to link MedicalHistory to PatientInfo automatically you need to use 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()

Views

class MedicalCreateView(CreateView):

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

Upvotes: 2

Related Questions