Django model data to JSON data in 2 lines

In this article, we are going to learn a handy trick to convert Django model data directly to JSON data. Sometimes, we need to return model data in JSON format; it can also be used in making API or just showing simple data to our frontend in JSON format. JSON is easy to access so it is really handful.


Create a Django project and an app.

In, add the app name in INSTALLED_APPS.

In of the Project main directory, add the following lines −

from django.contrib import admin
from django.urls import path,include

urlpatterns = [

Here we added our app's

In the App's, add the following lines −

from django.urls import path
from . import views
urlpatterns = [

Here we rendered our home view, which is simple.

In, add the following lines −

from django.db import models

# Create your models here.
class EmployeeData(models.Model):

Here, we created our model and add some dummy data for testing and trying.

In, add the following lines −

from django.contrib import admin
from .models import EmployeeData

# Register your models here.

Here, we simply registered our EmployeeData model in admin page.

In, add the following lines

from django.http import JsonResponse
from .models import EmployeeData
# Create your views here.
def home(request):
   return JsonResponse(data,safe=False)

Here, we created a list of all key-values using .value() function of our model data and then we rendered it as a JSON response.

Now it is all done, don't forget to add some random data.


      "id": 1,
      "name": "Ross Taylor",
      "Salary": "1 lakh",
      "department": "Technical"
      "id": 2,
      "name": "Rohit Sharma",
      "Salary": "2 lakh",
      "department": "Sales"
      "id": 3,
      "name": "Steve Smith",
      "Salary": "3 lakh",
      "department": "Sales"
Updated on 25-Aug-2021 13:04:38