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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With