Output Django queryset as JSON

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 get(self, request, *args, **kwargs):
        return HttpResponse(json.dumps({'data': [['bar','foo','bar','foo'],['foo','bar','foo','bar']]}, indent=4), content_type='application/json')

I simply don’t know how to output the queryset instead of the manual data in the example.

I’ve tried

json.dumps({"data": self.get_queryset()})

and

serializers.serialize("json", {'data': self.get_queryset()})

but it wont work. What am I doing wrong? Do I need to make a custom JSON Encoder?

Leave a Comment