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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With