Categories
Python Answers

How to output Python Django queryset as JSON?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *