I use Django 3.2.16 on Windows 11 then, I set '-c statement_timeout=5000' in OPTIONS and 'SET statement_timeout = 5000;' with cursor.execute() in settings.py 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',
# 'ATOMIC_REQUESTS': True,
},
'OPTIONS': {
'options': '-c statement_timeout=5000' # Here
}
}
cursor = connection.cursor()
cursor.execute('SET statement_timeout = 5000;') # Here
Then, test view with cursor.execute('SELECT pg_sleep(10);') below runs without any errors because statement_timeout = 5000 in settings.py doesn't work in test view:
# "views.py"
from django.db import connection
from django.http import HttpResponse
def test(request):
cursor = connection.cursor()
cursor.execute('SELECT pg_sleep(10);')
return HttpResponse("Test")
But, when setting statement_timeout = 5000 in test view as shown below:
# "views.py"
from django.db import connection
from django.http import HttpResponse
def test(request):
cursor = connection.cursor()
cursor.execute('SET statement_timeout = 5000;')
cursor.execute('SELECT pg_sleep(10);')
return HttpResponse("Test")
The error below occurs because statement_timeout = 5000 in test view works properly. *cursor.execute('SET statement_timeout = 5000;') only applies to test view rather than other views so you need to call cursor.execute('SET statement_timeout = 5000;') in each view if you want to apply cursor.execute('SET statement_timeout = 5000;') to each view:
django.db.utils.OperationalError: canceling statement due to statement timeout