Skip to content
Related Articles

Related Articles

Improve Article

How to Convert Models Data into JSON in Django ?

  • Last Updated : 16 Mar, 2021

Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design.  It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc.

How to Convert Models Data Into Json Data In Django ?

First create new project

django-admin startproject tryJson
cd tryJson

Then create new app inside your project

python startapp main

Add your main app inside the tryJson/ in INSTALLED_APPS

Edit the in main app


from django.db import models
class Student(models.Model):
    course_choices = (
    name = models.CharField(max_length=50)
    rollno = models.IntegerField()
    course = models.CharField(max_length=15,
        choices = course_choices)

Then to create model we have to write below commands in cmd or terminal

python makemigrations
python migrate

So we have created our model Students with some fields like name , roll no , course.

Insert Some data into model.

Create a new file inside your main app


from django.urls import path
from import *
urlpatterns = [
    path("",views.jsondata,name = "jsondata"),

Write logic to convert models data into Json data


from django.http import JsonResponse
from .models import Students
def jsondata(request):
      data list(Students.objects.values())
    return JsonResponse(data,safe = False)
  • Use values() method to get all the data and convert into list using list() function and store in a variable.
  • return a JsonResponse and pass the data and   put safe = False

Then  open cmd or terminal to run this app

python runserver

Output :-

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :