Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django atomic transaction not rolling back

I'm trying to do something like this:

with transaction.atomic():
    Model.objects.create(name="something")
    raise Exception

Since an exception is raised, this should mean that the transaction should roll back and the Model with name "something" should not exist.

However, if I query for Model.objects.get(name="something"), the object still exists in the db. Am I not understanding transactions correctly?

like image 801
cjxh Avatar asked Sep 06 '25 03:09

cjxh


1 Answers

I had the same issue recently and in my case it was because I was writing to a different database than the "default". I have a custom database router that selects the database depending on the request but both read and writes happen on the same database.

Note: All my models use the same database during the request.

From the django documentation, one must specify a database by providing using="database_alias" to the using block:

database_alias = ... # Get the database alias by using the same logic as in the router
with transaction.atomic(using=database_alias):
    Model.objects.create(name="something")
    raise Exception
like image 63
ErikM Avatar answered Sep 07 '25 16:09

ErikM