There are 2 ways to set REPEATABLE READ in Django.
<The 1st way (My recommendation)>
You can run the raw query to set isolation level anywhere in settings.py so I normally run the raw query just after database settings as shown below:
# "settings.py"
from django.db import connection
# ...
DATABASES = {
'default':{
'ENGINE':'django.db.backends.postgresql',
'NAME':'postgres',
'USER':'postgres',
'PASSWORD':'admin',
'HOST':'localhost',
'PORT':'5432',
},
}
# ↓ ↓ ↓ Set isolation level ↓ ↓ ↓
cursor = connection.cursor()
query = """
ALTER DATABASE postgres
SET DEFAULT_TRANSACTION_ISOLATION
TO 'REPEATABLE READ';
"""
cursor.execute(query)
# ↓ ↓ ↓ Check isolation level ↓ ↓ ↓
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 changing code so transaction is set every time Django Server is run with the command below or every time Django Server is reloaded by changing code:
python manage.py runserver 0.0.0.0:8000
<The 2nd way>
You can directly set REPEATABLE READ with psql as shown below:
postgres=# ALTER DATABASE postgres SET DEFAULT_TRANSACTION_ISOLATION TO 'REPEATABLE READ';
Actually, what the documentation explains as shown below doesn't work for me on Windows 11. That's why I show the 2 ways above:
# "settings.py"
import psycopg2.extensions
DATABASES = {
'default':{
'ENGINE':'django.db.backends.postgresql',
'NAME':'postgres',
'USER':'postgres',
'PASSWORD':'admin',
'HOST':'localhost',
'PORT':'5432',
},
'OPTIONS': {
'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
},
}
- 42.9k
- 23
- 259
- 259