Search code examples
pythondjangodjango-modelstransactionsdjango-database

Check for atomic context


One of my methods doesn't work when run on atomic context. I want to ask Django if it's running a transaction.

The method can create a thread or a process and saves the result to database. This is a bit odd but there is a huge performance benefit when a process can be used.

I find that especially processes are a bit sketchy with Django. I know that Django will raise an exception if the method chooses to save the results in a process and the method is run on atomic context.

If I can check for an atomic context then I can throw an exception straight away (instead of getting odd errors) or force the method to only create a thread.

I found the is_managed() method but according to this question it's been removed in Django 1.8.


Solution

  • According to this ticket there are a couple ways to detect this: not transaction.get_autocommit() (using a public API) or transaction.get_connection().in_atomic_block (using a private API).