Adding JSON field in Django models


In this article, we will see how to add JSON fields to our Django models. JSON is a simple format to store data in key and value format. It is written in curly braces. Many a time, on developer website, we need to add developer data and JSON fields are useful in such cases.

First create a Django project and an app. Please do all the basic things, like adding app in INSTALLED_APPS and setting up urls, making a basic model and render its form in an HTML file.

Example

Install the django-jsonfield package −

pip install django-jsonfield

Now, let's create a model in models.py, for example −

import jsonfield
from django.db import models

# Create your models here.

class StudentData(models.Model):
   name=models.CharField(max_length=100)
   standard=models.CharField(max_length=100)
   section=models.CharField(max_length=100)
   the_json = jsonfield.JSONField()

In admin.py, add the following lines −

from django.contrib import admin

from .models import StudentData

admin.site.register(StudentData)

We created a model here which has four fields, one of it is our thirdparty JSON field.

Now, run these commands −

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

These commands will create the table and the last command will create an admin user for you.

Now, you are all done.

Output

Go to http://127.0.0.1/admin/ and go to your model admin, then add an instance, you will see a field like this −

Updated on: 25-Aug-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements