Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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-value pairs using curly braces. JSON fields are particularly useful when you need to store flexible, unstructured data like user preferences, metadata, or configuration settings.
First, create a Django project and an app. Make sure to add your app to INSTALLED_APPS, set up URLs, and configure your basic project structure.
Modern Approach (Django 3.1+)
Django 3.1 and later versions include native JSON field support, eliminating the need for third-party packages ?
from django.db import models
class StudentData(models.Model):
name = models.CharField(max_length=100)
standard = models.CharField(max_length=100)
section = models.CharField(max_length=100)
metadata = models.JSONField(default=dict)
def __str__(self):
return self.name
Legacy Approach (Django < 3.1)
For older Django versions, you need to install the django-jsonfield package ?
pip install django-jsonfield
Then create your model ?
import jsonfield
from django.db import models
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()
def __str__(self):
return self.name
Admin Configuration
Register your model in admin.py to manage it through Django admin ?
from django.contrib import admin
from .models import StudentData
@admin.register(StudentData)
class StudentDataAdmin(admin.ModelAdmin):
list_display = ['name', 'standard', 'section']
Database Migration
Run these commands to create and apply migrations ?
python manage.py makemigrations python manage.py migrate python manage.py createsuperuser
Using JSON Fields
You can store and query JSON data directly ?
# Creating an instance with JSON data
student = StudentData.objects.create(
name="John Doe",
standard="10th",
section="A",
metadata={
"hobbies": ["reading", "swimming"],
"grades": {"math": 95, "science": 87},
"contact": {"email": "john@example.com"}
}
)
# Querying JSON field data
students_with_reading = StudentData.objects.filter(
metadata__hobbies__contains="reading"
)
Comparison
| Approach | Django Version | Package Required | Database Support |
|---|---|---|---|
| Native JSONField | 3.1+ | None | PostgreSQL, SQLite, MySQL |
| django-jsonfield | < 3.1 | Yes | Limited database support |
Conclusion
Use Django's native JSONField for modern projects (Django 3.1+) as it provides better performance and database support. For legacy projects, django-jsonfield remains a viable option for storing flexible JSON data.
