The Python Oracle

Django Transactions ATOMIC_REQUESTS

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping

--

Chapters
00:00 Django Transactions Atomic_requests
00:24 Accepted Answer Score 10
01:30 Answer 2 Score 1
02:03 Thank you

--

Full question
https://stackoverflow.com/questions/3173...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #django #djangoviews #transactions

#avk47



ACCEPTED ANSWER

Score 10


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()



ANSWER 2

Score 1


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.