Use JSONResponse to serialize a QuerySet in Django 1.7?

≯℡__Kan透↙ 提交于 2019-11-30 04:46:23
from django.core import serializers
from django.http import JsonResponse

def get_chat(request):
    usuario = request.GET.get('usuario_consultor', None)
    usuario_chat = request.GET.get('usuario_chat', None)

    mensajes = MensajeDirecto.objects.filter(Q(usuario_remitente = usuario, usuario_destinatario = usuario_chat) | Q(usuario_remitente = usuario_chat, usuario_destinatario = usuario))

    return JsonResponse(serializers.serialize('json', mensajes), safe=False)

Ref: https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects https://docs.djangoproject.com/en/1.7/topics/serialization/

You shouldn't re-serialize with JsonResponse. You'll get a correctly formatted JSON response with:

from django.core import serializers
from django.http import HttpResponse

def my_view(request):
    my_model = MyModel.objects.all()
    response = serializers.serialize("json", my_model)
    return HttpResponse(response, content_type='application/json')

If you use a JsonResponse, it will coerce the already serialized JSON to a string, which is probably not what you want.

Note: Works with Django 1.10

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