Django JSON field

Pawel Grajewski
2 min readJul 11, 2020

Django supports the PostgreSQL database it can be a default database for our project when we think about the production-ready project. One big advantage is the ability to store our data in the JSON field. This allowed us to use Django ORM and have the ability to aggregate on JSON fields. With a little trick, we can plug django-json-widget for custom data editing. Let’s start to create a docker container to work around creating PostgreSQL local environment and manage data migration when we will think about dock our project in the cloud.

Let’s start from creating a virtual environment for our project:

pipenv shell
pipenv install django psycopg2-binary django-json-widget
django admin-startproject postgresql_project

Next step is to create in root directory Dockerfile:

and docker-compose:

With this adjust we can start setting our project for container in settings.py:

Next, let’s build our project in the container :

docker-compose up -d --build
docker-compose exec web python manage.py migrate
docker-compose exec web python manage.py createsuperuser
docker-compose exec web python manage.py startapp JSONapp

Let’s add a model to our app:

Next forms.py:

Next views.py

Next admin.py:

Next urls.py

Next urls.py in the project folder:

The last thing is to create templates for our data:

Next contact.html

Next dog_delete.html:

Next dog_update.html

Next dogs_detail.html

Next dogs_list.html:

Next testcreate.html

Now we can migrate model and run our project:

docker-compose exec web python manage.py makemigrations
docker-compose exec web python manage.py migrate

And we are ready to go with Django CRUD app on json field next step will be add JSON schema and normal form for JSON field but this is out of this tutorial.

Another way to create data output as a JSON is to use buildIn Django JSON view:

This view can be starter for creating view :

And this when we want to have detail view with JSON:

The last view can handle JSON response depend on get argument:

Useful links:

--

--