Django DB Transactions

Hello everyone, I’m facing some issues right now. Actually I’m working on a project and want to set different isolation levels for different transactions. Some transactions which I do not care about, I want to set ISOLATION LEVEL as read uncommitted , for some SERIALIZABLE and for some REPEATABLE READ.

I was checking docs, but i the section django transactions i could see anything like this. Is this supported in Django ? If so can you please let me know how to do it?
Thanks

Hello @ashiqYousuf,

I would suggest defining multiple databases in your DATABASES settings, each definition with a meaning name and pointing to the same DB but passing different OPTIONS that configure the isolation level.

So then your logic would explicitely choose which database to use in each case.

Does this help?
Natalia.

Hi thanks for the response, but I want to know if I can do this within views, for certain queries like as

start transaction with isolation level read committed
Query 1
End transaction

start transaction with different isolation level
Query 2
End transaction

Like this.

Or for certain users having status = statisticians
I want to set isolation level repeatable read, let for api /getdata ad I don’t want the thicks and thins while he/she is analysing data.

And for same api I want to set isolation level read umcomiited for a normal user.

There shouldn’t be a need to define multiple database connections. You can use raw SQL to change the configured isloation level. For example, in a middleware using MariaDB you might do:

if request.user.status == "statistician":
    level = "REPEATABLE READ"
else:
    level = "READ UNCOMMITTED"
with connection.cursor() as c:
    c.execute(f"SET SESSION TRANSACTION ISOLATION LEVEL {level}")

@adamchainz thanks for your response. I’ll surely look into it.

Yea that seems to be a straightforward solution.