django 类型“TypeError”的对象不是JSON可序列化的

niwlg2el  于 2023-03-24  发布在  Go
关注(0)|答案(4)|浏览(194)

我尝试使用Django REST框架构建API
我得到了

type 'TypeError' is not JSON serializable

我该怎么做才能修好?
这是我的view.py

class NewsViewSet(viewsets.ModelViewSet):
    queryset = News.objects.all()
    serializer_class = NewsSerializer

    def list(self, request, **kwargs):
        try:
            nba = query_nba_by_args(**request.query_params)
            serializer = NewsSerializer(nba['items'], many=True)
            result = dict()
            result['data'] = serializer.data
            result['draw'] = nba['draw']
            result['recordsTotal'] = nba['total']
            result['recordsFiltered'] = nba['count']
            return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)

        except Exception as e:
            return Response(e, status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
fivyi3re

fivyi3re1#

Python异常不是json可序列化的。它在try中失败,因为一些连接或内容不可用的问题,然后进入except块,在那里你将异常e原样传递给Response(),所以这就是问题所在。解决方案-检查URL,并在except块中将异常e转换为字符串并传递给Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)

lyfkaqu1

lyfkaqu12#

except Exception as exception:
    return HttpResponse(exception)
1u4esq0p

1u4esq0p3#

Django无法将Exception对象转换为JSON格式并引发错误。要修复它,您应该将错误转换为字符串并将结果传递给响应:

except Exception as e:
    return Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
xqkwcwgp

xqkwcwgp4#

第一

import json
from django.http import HttpResponse

变更行

return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)

为了这个

return HttpResponse(json.dumps(result),content_type="application/json")

或使用

from django.http import JsonResponse

 return JsonResponse(json.dumps(result))

相关问题