Serializer do not send the related field

176 views Asked by At

I am using Django rest framework to create an API based on an already existed database. I am trying to send related field values for requests for the appointment model. All field data are sent, except the related field value. even no empty fields for that.

My models are:


class ExternalModel(models.Model):
    class Meta:
        managed = False
        abstract = True
        app_label = 'ctsql'

class Patients(ExternalModel):
    id = models.AutoField(db_column='ID', unique=True, primary_key=True)  # Field name made lowercase.
    inactive = models.BooleanField(db_column='InActive')  # Field name made lowercase.
    firstname = models.CharField(db_column='FirstName', max_length=35, blank=True, null=True)  # Field name made lowercase.
    middlename = models.CharField(db_column='MiddleName', max_length=20, blank=True, null=True)  # Field name made lowercase.
    lastname = models.CharField(db_column='LastName', max_length=35, blank=True, null=True)  # Field name made lowercase.
    inspatname = models.CharField(db_column='InsPatName', max_length=100, blank=True, null=True)  # Field name made lowercase.

    def __str__(self):
        return f'{self.firstname},{self.lastname}'
    class Meta:
        db_table = 'Patients'

class Contacts(ExternalModel):
    id = models.AutoField(db_column='ID', primary_key=True)  # Field name made lowercase.
    patientid = models.ForeignKey(Patients, models.DO_NOTHING, db_column='PatientID',related_name='patient_contact',related_query_name='patient_contact')  # Field name made lowercase.
    description = models.CharField(db_column='Description', max_length=25, blank=True, null=True)  # Field name made lowercase.
    number = models.CharField(db_column='Number', max_length=255, blank=True, null=True)  # Field name made lowercase.
    class Meta:
        db_table = 'ContactInfos'

class Appointments(ExternalModel):
    id = models.AutoField(db_column='ID', primary_key=True)  # Field name made lowercase.
    patientid = models.ForeignKey(Patients, models.DO_NOTHING, db_column='PatientID', related_name = 'patient_appointment')  # Field name made lowercase.
    scheduledatetime = models.DateTimeField(db_column='ScheduleDateTime', blank=True, null=True)  # Field name made lowercase.
    purposeofvisit = models.CharField(db_column='PurposeOfVisit', max_length=2500, blank=True, null=True)  # Field name made lowercase.
    appointmentnote = models.CharField(db_column='AppointmentNote', max_length=255, blank=True, null=True)  # Field name made lowercase.
    walkin = models.BooleanField(db_column='WalkIn')  # Field name made lowercase.
    status = models.SmallIntegerField(db_column='Status', blank=True, null=True)  # Field name made lowercase.
    reasoncancelled = models.CharField(db_column='ReasonCancelled', max_length=50, blank=True, null=True)  # Field name made lowercase.

    class Meta:
        db_table = 'Appointments'

My serializer is:

class appointmentSerializer(serializers.ModelSerializer):
    patientid_inspatname = serializers.RelatedField(source='patients', read_only=True)
    class Meta:
        model = Appointments
        fields = ['scheduledatetime','status','purposeofvisit','patientid_inspatname']

and my view is:

def appointment_detail(request):
    firstname = request.GET.get('firstname')
    firstname = firstname[:3]
    if not firstname:
        firstname = ''
    lastname = request.GET.get('lastname')
    lastname =lastname[:3]
    if not lastname:
        lastname = ''
    phonenumber = request.GET.get('phonenumber')
    if not phonenumber:
        phonenumber = ''
    date = request.GET.get('date')
    if date:
        date = datetime.strptime(date,'%m-%d-%Y').date()
        appointments = Appointments.objects.values('scheduledatetime','status','purposeofvisit','patientid__inspatname').filter(scheduledatetime__date=date,patientid__firstname__contains=firstname,patientid__lastname__contains=lastname,patientid__patient_contact__number__contains=phonenumber).order_by('-scheduledatetime')[:10]
    else:
        appointments = Appointments.objects.values('scheduledatetime','status','purposeofvisit','patientid__inspatname').filter(patientid__firstname__contains=firstname,patientid__lastname__contains=lastname,patientid__patient_contact__number__contains=phonenumber).order_by('-scheduledatetime')[:10]
    if not appointments:
        return HttpResponse(status=404)
    if request.method =='GET':
        serializer = appointmentSerializer(appointments, many=True)
        return JsonResponse(serializer.data, safe=False)

I tested my code with shell and everything works fine until I use serializer.data It will remove patientid__inspatname field from the response.

This is what I see:

[{"scheduledatetime": "2021-01-12T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT"}, {"scheduledatetime": "2021-01-12T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD"}, {"scheduledatetime": "2021-01-05T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT"}, {"scheduledatetime": "2021-01-05T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD"}, {"scheduledatetime": "2020-12-29T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT"}, {"scheduledatetime": "2020-12-29T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD"}, {"scheduledatetime": "2020-12-22T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD"}, {"scheduledatetime": "2020-12-22T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT"}, {"scheduledatetime": "2020-12-15T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT"}, {"scheduledatetime": "2020-12-15T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD"}]

and this is what I want:

[{"scheduledatetime": "2021-01-12T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT", "inspatname": ""}, {"scheduledatetime": "2021-01-12T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD", "inspatname": ""}, {"scheduledatetime": "2021-01-05T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT", "inspatname": ""}, {"scheduledatetime": "2021-01-05T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD, "inspatname": """}, {"scheduledatetime": "2020-12-29T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT", "inspatname": ""}, {"scheduledatetime": "2020-12-29T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD", "inspatname": ""}, {"scheduledatetime": "2020-12-22T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD", "inspatname": ""}, {"scheduledatetime": "2020-12-22T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT", "inspatname": ""}, {"scheduledatetime": "2020-12-15T16:30:00Z", "status": 1004, "purposeofvisit": "CHIRO ADJ/PT"}, {"scheduledatetime": "2020-12-15T16:30:00Z", "status": 1004, "purposeofvisit": "MEDICAL PTMD", "inspatname": ""}]

1

There are 1 answers

0
Amir Sabzehparvar On

To fix the issue, I changed the serializer to:

class appointmentSerializer(serializers.ModelSerializer):
patientid__inspatname = serializers.CharField(read_only=True)
class Meta:
    model = Appointments
    fields = ('scheduledatetime','status','purposeofvisit','patientid__inspatname')