Json无法在Django中序列化

时间:2018-10-13 17:13:53

标签: django

def ajax_leave_type_data(request):
    pk = request.GET.get('id', None)
    is_taken= Leave_Types.objects.filter(user_id=pk)
    return HttpResponse(json.dumps(is_taken), content_type='application/json')

那是我每次都遇到的错误,如果有人在我尝试了许多方法却无法解决之前遇到此问题,请给一些解决方案

Internal Server Error: /ajax/leave_ty
Traceback (most recent call last):
  File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/mnt/e/L_Management/Leave_Management_App/views.py", line 209, in ajax_leave_type_data
    return HttpResponse(json.dumps(is_taken), content_type='application/json')
  File "/usr/lib/python3.5/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.5/json/encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <QuerySet [<Leave_Types: Casual leaves>, <Leave_Types: Unpaid leaves>, <Leave_Types: Privilege leaves>, <Leave_Types: Sick leaves>]> is not JSON serializable
[13/Oct/2018 17:07:20] "GET /ajax/leave_ty?id=52&csrfmiddlewaretoken=3Fxb3n2PBMRSYWOgPLgRSWZzvQANFiFLTDihrZJ0HklK02YPU39C7eSGY5su7QKX HTTP/1.1" 500 15445

1 个答案:

答案 0 :(得分:0)

我将使用Django的JsonResponse

将其返回
from django.http import JsonResponse
def ajax_leave_type_data(request):
    pk = request.GET.get('id', None)
    is_taken= Leave_Types.objects.filter(user_id=pk)
    return JsonReponse({'is_taken': is_taken})