DjangoField: How to store semi-structured data with JSONFields in Django databases

Published on Aug. 22, 2023, 12:12 p.m.

One of the cool features that was introduced was the JSONField.JSONField allows for you to store semi-structured data alongside other data fields in PostgreSQL, and SQLite databases .The example in the listing below shows how the JSONField can be added to a model.

from django.db import models

class Patient(models.Model):
    name = models.CharField(max_length=256)
    data = models.JSONField()

# Create a patient instance
Patient(name='John Doe', data={
    'address': '123 Some House Number', 
    'city': 'Some City',
    'state': 'Utah',
})

# Filter and delete the patient
Patient.objects.filter(patient='John Doe', data__state='Utah')

The potential to mix structured and semi-structured data is really powerful, however, and there are a number of third-party fields implemented.

I thought that it would be nice if the API had the ability to query and filter the submissions.Implementing logic to provide that type of an interface on top of a CharField or TextField would be difficult.

Here’s before JSONField:

from django.db.models import TextField, Model

class FormSubmission(Model):
    ...
    form_data = TextField()

And after:

from django.db.models import TextField, JSONField, Model

class FormSubmission(Model):
    ...
    form_data = JSONField()

The upgrade was very smooth !Well done to the development team of Django - Development!