ip.
ip.

Reputation: 3314

Django Transactions ATOMIC_REQUESTS

I'm really unclear how atomic requests are set in Django. When ATOMIC_REQUESTS is set to True in the DB settings does that mean that all views now run in a transaction? What if I want only certain views to be run in a transaction? Do I then need to explicitly define all the others that are not run in a transaction with a @transaction.non_atomic_requests decorator?

Upvotes: 7

Views: 4617

Answers (2)

Yes, if 'ATOMIC_REQUESTS': True is set in settings.py, all views run in a transaction.

Yes, if @transaction.non_atomic_requests decorator is set to a view, the view doesn't run in a transaction even if 'ATOMIC_REQUESTS': True is set in settings.py.

In addition, Django admin is run in a transaction by default whether or not 'ATOMIC_REQUESTS': True is set in settings.py.

Upvotes: 1

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48982

When ATOMIC_REQUESTS is set to True in the DB settings does that mean that all views now run in a transaction?

Yes. From the docs:

Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction.

Do I then need to explicitly define all the others that are not run in a transaction with a @transaction.non_atomic_requests decorator?

Yes.

When ATOMIC_REQUESTS is enabled, it’s still possible to prevent views from running in a transaction. [The non_atomic_requests] decorator will negate the effect of ATOMIC_REQUESTS for a given view.

Once you're at the point of deciding on a case-by-case basis where transactions should be used, though, I prefer to not use ATOMIC_REQUESTS and just use transaction.atomic (whether as a decorator or a context manager) where appropriate. Here's an example from the documentation:

@transaction.atomic
def viewfunc(request):
    # This code executes inside a transaction.
    do_stuff()

Upvotes: 10

Related Questions