Menu Close

How to output Python Django queryset as JSON?

Sometimes, we want to output Python Django queryset as JSON.

In this article, we’ll look at how to output Python Django queryset as JSON.

How to output Python Django queryset as JSON?

To output Python Django queryset as JSON, we can serialize our queryset as JSON with Django’s built in serializers.

For instance, we write

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')

to call serializers.serialize with 'json' and queryset qs to return the qs_json JSON string.

And then we create a HttpResponse object with that and return it as the response in our view.

Conclusion

To output Python Django queryset as JSON, we can serialize our queryset as JSON with Django’s built in serializers.

Posted in Python, Python Answers