Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JSONResponse to serialize a QuerySet in Django 1.7?

Tags:

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?

like image 588
Cris_Towi Avatar asked Oct 15 '14 03:10

Cris_Towi


People also ask

How do you serialize a Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

What does JsonResponse do in Django?

Django JsonResponse JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data , should be a dict instance.


1 Answers

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

like image 108
Daniel van Flymen Avatar answered Oct 09 '22 06:10

Daniel van Flymen