Open In App

How to Output Django QuerySet as JSON

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Step By Step Guide to Output Django QuerySet as JSON

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.

Step 1: Install Django

First, ensure that Django is installed:

pip install django

Step 2: Create a New Django Project

Create 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

Python
INSTALLED_APPS = [
    # ...,
    'myapp',
]

Step 3: Define a Django Model

In myapp/models.py, create a simple model:

Python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title

Step 4: Create and Apply Migrations

Run migrations to set up the database:

python manage.py makemigrations
python manage.py migrate

Step 5: Add Some Data

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.

orm-
Using Django Shell

1. Serialize Django QuerySet using Serializer

Django’s serializers module can be used to serialize a QuerySet to JSON.

Step 1: Define the View

In myapp/views.py, we’ll create a view that serializes a QuerySet to JSON:

  • We use serializers.serialize() to convert the QuerySet into JSON format.
  • The HttpResponse() sends the serialized JSON as the response, with content_type='application/json' to specify the content type.

Note: The serializers.serialize() method takes a queryset not a single object and returns data in the valid defined format.

Python
from django.http import HttpResponse
from django.core import serializers
from .models import Book

def book_list(request):
    queryset = Book.objects.all()
    data = serializers.serialize('json', queryset)
    return HttpResponse(data, content_type='application/json')

Step 2: Set up the URL

In urls.py, define the URL for the book_list view:

Python
from django.contrib import admin
from django.urls import path
from myapp.views import book_list

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', book_list_json, name='book_list_json'),
]

Run the Server

python manage.py runserver

If we access the /books/ URL, we’ll get a response similar to:

serializers
Json response in Django

2. Serialize Django QuerySet using JsonResponse

Another method to output JSON in Django is by using the JsonResponse class, which automatically converts Python dictionaries into JSON format.

Step 1: Define the View with JsonResponse

In myapp/views.py, create a new view using JsonResponse:

  • We use the .values() method to retrieve a QuerySet of dictionaries containing only the fields we need (title, author, published_date).
  • JsonResponse automatically serializes the Python list into JSON format.
  • The safe=False parameter is required because by default, JsonResponse only accepts dictionaries, not lists.
Python
from django.http import JsonResponse
from .models import Book

def book_list_json(request):
    queryset = Book.objects.all().values('title', 'author', 'published_date')
    
    # Convert QuerySet to a list of dictionaries
    data = list(queryset)
    return JsonResponse(data, safe=False)

Step 2: Set up the URL

In urls.py, define the URL for the book_list_json view:

Python
from django.contrib import admin
from django.urls import path
from myapp.views import book_list_json

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books-json/', book_list_json, name='book_list_json'),
]

Run the Server

python manage.py runserver

If we access the /books-json/ URL, we’ll get a response like:

second
Using JSONResponse to send data in Django

Conclusion

In this article, we covered two methods to output Django QuerySets as JSON:

  1. Using Django’s serializers: This method provides a full representation of the model, including metadata like the model name and primary key.
  2. Using JsonResponse: A simpler approach that directly outputs the QuerySet as a list of dictionaries, suitable for lightweight API responses.

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.


Next Article

Similar Reads