首页 > 解决方案 > TypeError:“_Serializer”类型的对象不是 JSON 可序列化的

问题描述

我在 Django rest api 中比较新。我的代码如下:

class PatientViewSet(viewsets.ModelViewSet):
queryset = Patient.objects.all()
serializer_class = PatientSerializer
filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
filterset_fields = ['id', 'email', 'mobile', 'status', 'type', 'gender']
ordering_fields = ['id', 'name']

def get_queryset(self):
    queryset = Patient.objects.all()
    status = self.request.query_params.get('status')
    name = self.request.query_params.get('name')
    if not status:
        queryset = queryset.exclude(status="DELETE")
    if name:
        queryset = queryset.filter(name__icontains=name)
    return queryset

def retrieve(self, request, pk=None):
    queryset = Patient.objects.all()
    patient = get_object_or_404(queryset, pk=pk)
    serializer = PatientSerializer(patient)

    summary = dict()
    summary['payment'] = list(PatientPayment.objects.filter(patient_id=pk).aggregate(Sum('amount')).values())[0]
    summary['appointment'] = DoctorAppointment.objects.filter(patient_id=pk).count()

    d_appoint = DoctorAppointment.objects.filter(patient__id=pk).last()
    appoint_data = DoctorAppointmentSerializer(d_appoint)

    summary['last_appointment'] = appoint_data

    content = {"code": 20000, "data": serializer.data, "summary": summary}
    return Response(content)

这里的网址是:

http://127.0.0.1:8000/api/patients/2/

当我在邮递员中运行时,出现以下错误:

/api/patients/2/ 上的 TypeError 类型“DoctorAppointmentSerializer”的对象不是 JSON 可序列化的

这里代码片段的问题:

d_appoint = DoctorAppointment.objects.filter(patient__id=pk).last()
appoint_data = DoctorAppointmentSerializer(d_appoint)

我的问题是我怎样才能得到我的结果?

DoctorAppointmentSerializer 类:

class DoctorAppointmentSerializer(serializers.HyperlinkedModelSerializer):
patient = PatientSerializer(read_only=True)
patient_id = serializers.IntegerField()
doctor = DoctorSerializer(read_only=True)
doctor_id = serializers.IntegerField()
doc_image = Base64ImageField(
    allow_null=True, max_length=None, use_url=True, required=False
)
doc_file = Base64ImageField(
    allow_null=True, max_length=None, use_url=True, required=False
)

class Meta:
    model = DoctorAppointment
    fields = ['id', 'name', 'mobile', 'problem', 'age', 'gender', 'description', 'doctor', 'doctor_id', 'patient',
              'patient_id', 'advice', 'doc_image', 'doc_file', 'created_at']

标签: djangoapi

解决方案


你必须调用类的.data属性DoctorAppointmentSerializer

appoint_data = DoctorAppointmentSerializer(d_appoint).data
                                                  ^^^^^^

推荐阅读