![]() |
VOOZH | about |
In Django, a common task for web developers is to return data in JSON format, especially when working with APIs. A Django QuerySet, which is a collection of database queries, can be serialized and output as JSON. This article will guide us through how to output a Django QuerySet as JSON using two methods:
Before diving into the examples, let’s set up a Django project to demonstrate how to output QuerySet as JSON. If you already have a Django project, you can skip this step.
First, ensure that Django is installed:
pip install djangoCreate a new project and app:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
Add myapp to the INSTALLED_APPS in settings.py file
In myapp/models.py, create a simple model:
Run migrations to set up the database:
python manage.py makemigrations
python manage.py migrate
We can add some sample data using Django’s shell:
python manage.py shell
>>>from myapp.models import Book
>>>Book.objects.create(title="The Great Gatsby", author="F. Scott Fitzgerald", published_date="1925-04-10")
>>>Book.objects.create(title="To Kill a Mockingbird", author="Harper Lee", published_date="1960-07-11")
Now that we have some data in the database, let's move on to outputting a QuerySet as JSON.
Django’s serializers module can be used to serialize a QuerySet to JSON.
In myapp/views.py, we’ll create a view that serializes a QuerySet to JSON:
Note: The serializers.serialize() method takes a queryset not a single object and returns data in the valid defined format.
In urls.py, define the URL for the book_list view:
python manage.py runserverIf we access the /books/ URL, we’ll get a response similar to:
Another method to output JSON in Django is by using the JsonResponse class, which automatically converts Python dictionaries into JSON format.
In myapp/views.py, create a new view using JsonResponse:
In urls.py, define the URL for the book_list_json view:
python manage.py runserverIf we access the /books-json/ URL, we’ll get a response like:
In this article, we covered two methods to output Django QuerySets as JSON:
Both methods are useful, depending on the specific requirements of our project. If we need complete control over how the data is structured, JsonResponse is a flexible option, whereas serialization is more suitable for cases where model metadata is important.