How to use postgresql jsonb type with django

Introduction

In this tutorial, we are going to use jsonb column type that was introduced in postgresql 9.5. We will use django web framework model that uses jsonb column.

jsonb is a column type that support natively json format and using this column type avoids breaking the normalization rule nro 1.

PostgreSQL allows you to do queries on the json data stored in the column. Using this type of column allows you to have flexibility in with sql schemas.

Using Django JSONField

Django has a JSONField in django.contrib.postgres.fields You can create a model that uses this column:

from django.contrib.postgres.fields import JSONField
from django.db import models
class Car(models.Model):
    name = models.TextField()
    data = JSONField()

Once you declare this you can use the data attribute as a schemaless dicitonary using postgresql.

Using model with json column

car=Car.objects.create(name=”Civic”)
car.data = {“year”: “2009”, “engine_state”: “bad”}
car.save()

You can also do queries using data json keys, you need to use __ with nested fields:

Car.objects.filter(data__engine_state=”bad”)

You can also query null values using:

Car.objects.filter(data__engine_state=None)