}

How to use postgresql jsonb type with django

Created:

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() if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-tutorials_technology-medrectangle-3-0')}; 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:

if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-tutorials_technology-medrectangle-4-0')};Car.objects.filter(data__engine_state=None)