IntegrityError at /clinic_management/patients/1/medhistory/ NOT NULL constraint failed

Hi folks, beginner to django here
I’m trying to create an app which stores medical records of patients. I’m trying to get information about the patient but I have encountered a problem.
When it comes to posting the medical history I receive the following error:

“IntegrityError at /clinic_management/medhistory/ NOT NULL constraint failed: clinic_management_medical_history.patient_id”

models.py
class PatientPersonalInfo(models.Model):
    file_number = models.IntegerField(unique=True)
    identification_number = models.IntegerField(unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    father_name = models.CharField(max_length=50)
    birth_date = models.DateField(null=True, blank=True)
    occupation = models.CharField(max_length=50)
    phone = models.IntegerField()
    mobile_phone = models.IntegerField()
    address = models.TextField(null=True, blank=True)

class Medical_history(models.Model):
    ailment = models.CharField(max_length=50)
    hospitalization_history = models.CharField(max_length=50)
    hospitalization_cause = models.TextField(null=True, blank=True)
    medication_use = models.CharField(max_length=50)
    patient = models.OneToOneField(PatientPersonalInfo, on_delete=models.CASCADE)
views.py
class PatientPersonalInfoViewSet(ModelViewSet):
    queryset = PatientPersonalInfo.objects.all()
    serializer_class = PatientPersonalInfoSerializer
    pagination_class = DefaultPagination
    search_fields = ['file_number', 'identification_number', 'last_name']

class MedicalHistoryViewSet(ModelViewSet):
    queryset = Medical_history.objects.all()
    serializer_class = MedicalHistorySerializer
serializers.py
class PatientPersonalInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = PatientPersonalInfo
        fields = ['id', 'file_number', 'first_name', 'last_name', 'father_name',
                'identification_number', 'birth_date', 'phone', 'mobile_phone']

 
class MedicalHistorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Medical_history
        fields = ['ailment', 'hospitalization_history', 'hospitalization_cause', 'medication_use']

Any help is appreciated in advance.

What does the data being submitted look like?

Your MedicalHistorySerializer doesn’t provide for the patient field in the MedicalHistory model.

1 Like