Store dict in database django

Published on and updated on
by

Storing dictionary in database in Django. There are a couple of ways to do that. In this guide, we're going to look at storing dict in database using JSONField.

Storing dictionary in database in Django. There are a couple of ways to do that. In this guide, we're going to look at storing dict in database using JSONField.  Let's start from the beginning and create a sample project.

mkvirtualenv testprod
pip install django
django-admin startproject testblog
cd testblog

Now, that we have sample django project called testblog. Let's migrate the default migrations.

python manage.py migrate

Create an app named core:

python manage.py startapp core

Registering the app in project's settings.py file.

vim testblog/settings.py

And the app inside INSTALLED_APPS:

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "core",
]

Now, let's create Blog model with JSONField.

vim core/models.py
from django.db import models

class Blog(models.Model): 
    title = models.CharField(max_length=100)
    data = models.JSONField(null=True)
    
    def __str__(self):
        return self.title

Create migrations and apply them to the database.

python manage.py makemigrations
python manage.py migrate

How to store dict in django database?

Creating some sample entries in our Blog model. Also storing dict in django database using the JSONField.

  • JSONField: A field for storing JSON encoded data. In Python the data is represented in its Python native format: dictionaries, lists, strings, numbers, booleans and None.
  • JSONField is supported on MariaDB 10.2.7+, MySQL 5.7.8+, Oracle, PostgreSQL, and SQLite (with the JSON1 extension enabled).

You can learn more about JSONField at Django's official documentation.

>>> b1 = Blog.objects.create(title="Obama", data={"occupatiion": "former president", "age": 18})
>>> b1
<Blog: Obama>
>>> print(b1.title)
Obama

How to query dict from django database?

Fetching dict from django database is quite simple as you fetch normally in JavaScript with JSON object.

>>> b1.data["age"]
18
>>> b1.data["occupatiion"]
'former president'

You can also use Django's get() method and filter() method or any other method that you usually use query from database. You just have to treat it as JSON object.