Output Django queryset as JSON

后端 未结 6 1719
陌清茗
陌清茗 2020-11-29 01:20

I want to serialize my queryset, and I want it in a format as this view outputs:

class JSONListView(ListView):
    queryset = Users.objects.all()

    def ge         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 01:56

    You can use JsonResponse with values. Simple example:

    from django.http import JsonResponse
    
    def some_view(request):
        data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable
        return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})
    

    Or another approach with Django's built-in serializers:

    from django.core import serializers
    from django.http import HttpResponse
    
    def some_view(request):
        qs = SomeModel.objects.all()
        qs_json = serializers.serialize('json', qs)
        return HttpResponse(qs_json, content_type='application/json')
    

    In this case result is slightly different (without indent by default):

    [
        {
            "model": "some_app.some_model",
            "pk": 1,
            "fields": {
                "name": "Elon",
                "age": 48,
                ...
            }
        },
        ...
    ]
    

    I have to say, it is good practice to use something like marshmallow to serialize queryset.

    ...and a few notes for better performance:

    • use pagination if your queryset is big;
    • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);

提交回复
热议问题