Cris_Towi
Cris_Towi

Reputation: 625

Use JSONResponse to serialize a QuerySet in Django 1.7?

I saw that now in Django 1.7 I can use the http.JSONResponse object to send JSON to a client. My View is:

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

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


    return JsonResponse(mensajes, safe=False)

But I get the next error:

<MensajeDirecto: Towi CrisTowi> is not JSON serializable`

Do you know how to serialize a QuerySet to send it back in JSON form?

Upvotes: 25

Views: 32530

Answers (3)

nurettin
nurettin

Reputation: 11736

You don't need serialize. It will mangle the data, add a bunch of useless dictionary keys like model name, pk and fields.

instead of this

return JsonResponse(mensajes, safe=False)

just do this (mensajes = MensajeDirecto.objects.filter..)

return JsonResponse({"mensajes": list(mensajes.values())})

This way, you are not returning a list, you are returning a valid json, so you can use safe=True which is default. You can also return other messages to show on the frontend such as {"mensajes": ..., "error": "invalid request" }

Upvotes: 0

Daniel van Flymen
Daniel van Flymen

Reputation: 11541

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

Upvotes: 69

micrypt
micrypt

Reputation: 431

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/

Upvotes: 16

Related Questions