4

When I am trying to send values in JsonResponse then The error is coming(object of type QuerySet is not JSON serializable )

def ajaxAgent(request):
    data = CommCenter.objects.values()
    responseData = { 'status': 'success', 'msg' : data}
    return JsonResponse(responseData)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
vipul
  • 87
  • 1
  • 1
  • 9
  • 1
    Does this answer your question? [Output Django queryset as JSON](https://stackoverflow.com/questions/15874233/output-django-queryset-as-json) – Vadorequest Nov 08 '19 at 11:26

3 Answers3

7

Please find here the answer:

from django.http import JsonResponse

def some_view(request):
    data = list(SomeModel.objects.values())
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})
Hugo Martin
  • 167
  • 6
2

What worked for me was using values_list() and converting to list using list

def ajaxAgent(request):
    data = CommCenter.objects.filter().values_list()
    responseData = { 'status': 'success', 'msg' : list(data)}
    return JsonResponse(responseData)
MattG
  • 1,682
  • 5
  • 25
  • 45
0

You will have to write a model serializer to serialize the values of the objects into JSON that are returned to you as list when you fetch objects using Django ORM. Check this link out for more details ModelSerializer

satyam soni
  • 259
  • 1
  • 9