django - 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']
解决方案
你必须调用类的.data
属性DoctorAppointmentSerializer
appoint_data = DoctorAppointmentSerializer(d_appoint).data
^^^^^^
推荐阅读
- python - 生成器中的程序控制流程如何?
- c# - 实体框架 - 是否可以在不同的 AppDomain 之间共享存储在内存中的 DbCompiledModel 和元数据信息?
- hex - 将#hex 转换为 0xFF-hex
- anypoint-studio - Anypoint CLI VS ARM REST 服务(自动部署首选哪一种?)使用 Cloud Console 本地部署
- arrays - 尝试删除数组 vba 中的元素时出现错误 424
- java - 如何删除“线性布局”中的渐变边框?
- npm - npm:确认这种情况下 npm install 的行为?为什么没有嵌套依赖?
- amazon-web-services - AWS S3 Rest API:无法上传对象
- javascript - 如何根据语义 UI 下拉列表中的选定项目更改页面上的文本?
- fullcalendar - 关于构建类似于 FullCalander 演示中显示的左侧菜单栏的建议