Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to Convert Models Data into JSON in Django ?

How to Convert Models Data into JSON in Django ?

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 manage.py startapp main

Add your main app inside the tryJson/settings.py in INSTALLED_APPS

Edit the models.py in main app

Python3




from django.db import models
  
class Student(models.Model):
    course_choices = (
        ('1','Java'),
        ('2','Python'),
        ('3','Javascript')
        )
    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 manage.py makemigrations
python manage.py 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 

urls.py

Python3




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


Write logic to convert models data into Json data

views.py

Python3




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 manage.py runserver

Output :-

RELATED ARTICLES

Most Popular

Recent Comments