diff options
| author | Jonatas CD <jonatas.cd@gmail.com> | 2017-09-04 21:43:29 +0200 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2017-09-04 15:43:42 -0400 |
| commit | 02210393097b0183ad2a462dbdfb900e450327eb (patch) | |
| tree | 0d27ef3da8da35281ed0509a52a1e4aca7083012 | |
| parent | ddea2166f1db776dadbc26751b8ceaba3cace6b5 (diff) | |
[1.11.x] Fixed #28479 -- Doc'd that transaction rollback doesn't revert model state.
Backport of c9b22707b0703db6c6ddaebdd00e2cd33d182e40 from master
| -rw-r--r-- | docs/topics/db/transactions.txt | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index 0f028dd343..36391c92f4 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -176,6 +176,29 @@ Django provides a single API to control database transactions. If you catch exceptions raised by raw SQL queries, Django's behavior is unspecified and database-dependent. + .. admonition:: You may need to manually revert model state when rolling back a transaction. + + The values of a model's fields won't be reverted when a transaction + rollback happens. This could lead to an inconsistent model state unless + you manually restore the original field values. + + For example, given ``MyModel`` with an ``active`` field, this snippet + ensures that the ``if obj.active`` check at the end uses the correct + value if updating ``active`` to ``True`` fails in the transaction:: + + from django.db import DatabaseError, transaction + + obj = MyModel(active=False) + obj.active = True + try: + with transaction.atomic(): + obj.save() + except DatabaseError: + obj.active = False + + if obj.active: + ... + In order to guarantee atomicity, ``atomic`` disables some APIs. Attempting to commit, roll back, or change the autocommit state of the database connection within an ``atomic`` block will raise an exception. |
