问题
How can I return JSON response of model queryset from a view using django serializer ?
from django.core import serializers
from django.http.response import JsonResponse
def some_view(request):
qs = SomeModel.objects.all()
serialized_obj = serializers.serialize('json', qs)
return JsonResponse(serialized_obj, safe=False)
According to code snippet, the view producess a non-json response.
回答1:
This can be easily done by using python
format.
serialized_obj = serializers.serialize('python', qs)
Unfortunately, Django serializer doc doesn't mention anything about it, but the source code does
来源:https://stackoverflow.com/questions/56025553/serialize-django-model-queryset-with-serializers-serialize-function