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
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
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
Write logic to convert models data into Json data
- 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