【问题标题】:Serializer do not send the related field序列化器不发送相关字段
【发布时间】:2021-03-13 16:27:45
【问题描述】:

我正在使用 Django rest 框架来创建一个基于已经存在的数据库的 API。我正在尝试为预约模型的请求发送相关字段值。发送所有字段数据,相关字段值除外。甚至没有空字段。

我的模型是:


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'

我的序列化器是:

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

我的观点是:

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)

我用 shell 测试了我的代码,一切正常,直到我使用 serializer.data 它将从响应中删除 patientid__inspatname 字段。

这是我看到的:

[{"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"}]

这就是我想要的:

[{"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": ""}]

【问题讨论】:

    标签: json api django-rest-framework django-serializer jsonresponse


    【解决方案1】:

    为了解决这个问题,我将序列化程序更改为:

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

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多