Use JSONResponse to serialize a QuerySet in Django 1.7?

前端 未结 2 1068
广开言路
广开言路 2020-12-29 05:15

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):
    usuar         


        
2条回答
  •  一整个雨季
    2020-12-29 05:49

    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

提交回复
热议问题