深度阅读

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

作者
作者
2023年08月22日
更新时间
13.98 分钟
阅读时间
0
阅读量

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!

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。