Django Transactions ATOMIC_REQUESTS
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
00:38 Accepted answer (Score 10)
02:09 Answer 2 (Score 0)
02:46 Thank you
--
Full question
https://stackoverflow.com/questions/3173...
Accepted answer links:
[docs]: https://docs.djangoproject.com/en/1.8/to...
[the documentation]: https://docs.djangoproject.com/en/1.8/to...
--
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_REQUESTSis enabled, it’s still possible to prevent views from running in a transaction. [Thenon_atomic_requests] decorator will negate the effect ofATOMIC_REQUESTSfor 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.