Python 使用 JSONResponse 在 Django 1.7 中序列化 QuerySet?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26373992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:25:07  来源:igfitidea点击:

Use JSONResponse to serialize a QuerySet in Django 1.7?

pythonajaxdjangojsonresponse

提问by Cris_Towi

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

我现在在 Django 1.7 中看到我可以使用该http.JSONResponse对象将 JSON 发送到客户端。我的观点是:

#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`

<MensajeDirecto: Towi CrisTowi> 不是 JSON 可序列化的`

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

您知道如何序列化 QuerySet 以将其以 JSON 形式发回吗?

采纳答案by micrypt

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-objectshttps://docs.djangoproject.com/en/1.7/topics/serialization/

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

回答by Daniel van Flymen

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

您不应该使用JsonResponse. 您将获得格式正确的 JSON 响应:

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.

如果您使用 a JsonResponse,它会将已经序列化的 JSON 强制转换为字符串,这可能不是您想要的。

Note: Works with Django 1.10

注意:适用于 Django 1.10