serialize django model queryset with serializers.serialize() function

淺唱寂寞╮ 提交于 2019-12-24 08:59:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!