[Fixed]-Create JSON Response in Django with Model

19👍

You should use django serializers instead of simplejson:

For example, this returns correctly serialized data:

from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('json', some_queryset)
# serialize object
serialized_object = serializers.serialize('json', [some_object,])

17👍

Method-1: Use Django’s python serializer

I think this answer won’t return a JSON or a Python dict/list object. So, use the format python instead of json

from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('python', some_queryset)
# serialize object
serialized_object = serializers.serialize('python', [some_object,])

Django shell response

In [2]: from django.core import serializers                                                                                                                             

In [3]: qs = SomeModel.objects.all()                                                                                                                                    

In [4]: json_res = serializers.serialize('json',qs)                                                                                                                     

In [5]: type(json_res)                                                                                                                                                  
Out[5]: str

In [6]: python_res = serializers.serialize('python',qs)                                                                                                                 

In [7]: type(python_res)                                                                                                                                                
Out[7]: list
#views.py
from django.core import serializers
from django.http.response import JsonResponse


def some_view(request):
    some_queryset = SomeModel.objects.all()
    serialized_queryset = serializers.serialize('python', some_queryset)
    return JsonResponse(serialized_queryset, safe=False)

Method-2: Use Django’s values() method

The direct use of values() method will throw TypeError exception, so convert the QuerySet to a python list as below,

from django.http.response import JsonResponse


def sample_view(request):
    return JsonResponse(list(SomeModel.objects.all().values()), safe=False)
👤JPG

Leave a comment