Default isolation level for transaction (@atomic) with Django and PostgreSQL

Question:

I was wondering what’s the default isolation level when using Django with PostgreSQL. Serializable Isolation? (https://www.postgresql.org/docs/9.1/static/transaction-iso.html#XACT-SERIALIZABLE)

There is a discussion about MySQL (Django transaction isolation level in mysql & postgresql) but despite its name is doesn’t seem to discuss PostgreSQL

Thanks!

Asked By: Alex Vyushkov

||

Answers:

From the docs:

Like PostgreSQL itself, Django defaults to the READ COMMITTED
isolation level.

Answered By: Nick Barnes

Django can be configured using the database settings like this:

import psycopg2.extensions

DATABASES = {
    # ...
    'OPTIONS': {
        'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
    },
}

Documentation – https://docs.djangoproject.com/en/2.2/ref/databases/#isolation-level

Answered By: danizen

According to my test, Django’s default isolation level depends on the isolation level which you set for your PostgreSQL. In other words, if you set REPEATABLE READ for your PostgreSQL with psql, Django’s default isolation level is REPEATABLE READ.

With the raw query below, you can check the current isolation level of your PostgreSQL from settings.py in Django. *The raw query must be run after database settings otherwise error occurs:

# "settings.py"

from django.db import connection

# ...

DATABASES = {
    'default':{
        'ENGINE':'django.db.backends.postgresql',
        'NAME':'postgres',
        'USER':'postgres',
        'PASSWORD':'admin',
        'HOST':'localhost',
        'PORT':'5432',
    },
}

cursor = connection.cursor()
cursor.execute('SHOW default_transaction_isolation;')
print(cursor.fetchone()) # ('repeatable read',)

*settings.py is run every time Django Server is run with the command below or every time Django Server is reloaded by writing code so the raw query above is run every time Django Server is run with the command below or every time Django Server is reloaded by writing code:

python manage.py runserver 0.0.0.0:8000

In addition, you can also see my answer explaining how to set the isolation level of PostgreSQL from Django.

Answered By: Kai – Kazuya Ito