|
| 1 | +.. _django-transactions: |
| 2 | + |
| 3 | +========================= |
| 4 | +Transactions and Sessions |
| 5 | +========================= |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: code example, ACID compliance, multi-document |
| 13 | + |
| 14 | +.. contents:: On this page |
| 15 | + :local: |
| 16 | + :backlinks: none |
| 17 | + :depth: 2 |
| 18 | + :class: singlecol |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +In this guide, you can learn how to use {+django-odm+} to perform |
| 24 | +**transactions**. Transactions allow you to run a series of operations |
| 25 | +that change data only if the entire transaction is committed. |
| 26 | +If any operation in the transaction does not succeed, {+django-odm+} stops the |
| 27 | +transaction and discards all changes to the data before they ever become |
| 28 | +visible. This feature is called **atomicity**. |
| 29 | + |
| 30 | +In MongoDB, transactions run within logical sessions. A |
| 31 | +session is a grouping of related read or write operations that you |
| 32 | +want to run sequentially. Sessions enable causal consistency for a group |
| 33 | +of operations and allow you to run operations in an **ACID-compliant** |
| 34 | +transaction, which is a transaction that meets an expectation of |
| 35 | +atomicity, consistency, isolation, and durability. |
| 36 | + |
| 37 | +You can use {+framework+}'s transaction API to perform database transactions. |
| 38 | +To run operations within a transaction, define them inside an atomic block of |
| 39 | +code. {+framework+} manages session logic internally, so you do not need to |
| 40 | +manually start a session before running a transaction. |
| 41 | + |
| 42 | +.. important:: Transaction Limitations |
| 43 | + |
| 44 | + {+django-odm+}'s support for the {+framework+} transaction API |
| 45 | + has several limitations. To view a list of limitations, see |
| 46 | + :ref:`Database and Collection Support <django-feature-compat-db-coll>` |
| 47 | + in the {+framework+} and MongoDB Feature Compatibility guide. |
| 48 | + |
| 49 | +Sample Data |
| 50 | +~~~~~~~~~~~ |
| 51 | + |
| 52 | +The examples in this guide use the ``Movie`` model, which represents |
| 53 | +the ``sample_mflix.movies`` collection from the :atlas:`Atlas sample datasets </sample-data>`. |
| 54 | +The ``Movie`` model class has the following definition: |
| 55 | + |
| 56 | +.. literalinclude:: /includes/interact-data/crud.py |
| 57 | + :start-after: start-models |
| 58 | + :end-before: end-models |
| 59 | + :language: python |
| 60 | + :copyable: |
| 61 | + |
| 62 | +.. include:: /includes/use-sample-data.rst |
| 63 | + |
| 64 | + .. replacement:: model-classes |
| 65 | + |
| 66 | + ``Movie`` model includes |
| 67 | + |
| 68 | + .. replacement:: model-imports |
| 69 | + |
| 70 | + .. code-block:: python |
| 71 | + |
| 72 | + from <your application name>.models import Movie |
| 73 | + from django.utils import timezone |
| 74 | + from datetime import datetime |
| 75 | + |
| 76 | +Start a Transaction |
| 77 | +------------------- |
| 78 | + |
| 79 | +To start a database transaction, define an atomic block of code |
| 80 | +by adding the ``@transaction.atomic`` decorator above your function. |
| 81 | +This decorator guarantees the atomicity of any database operations |
| 82 | +within the function. If the function successfully completes, the |
| 83 | +changes are committed to MongoDB. |
| 84 | + |
| 85 | +The following example calls the ``create()`` method within a transaction, |
| 86 | +which inserts a document into the ``sample_mflix.movies`` collection if the |
| 87 | +transaction succeeds: |
| 88 | + |
| 89 | +.. literalinclude:: /includes/interact-data/transactions.py |
| 90 | + :start-after: start-transaction-decorator |
| 91 | + :end-before: end-transaction-decorator |
| 92 | + :language: python |
| 93 | + :copyable: |
| 94 | + |
| 95 | +Alternatively, you can use the ``transaction.atomic()`` context manager |
| 96 | +to create an atomic block. This example runs the same operation as the |
| 97 | +preceding example but uses a context manager to start a transaction: |
| 98 | + |
| 99 | +.. literalinclude:: /includes/interact-data/transactions.py |
| 100 | + :start-after: start-transaction-manager |
| 101 | + :end-before: end-transaction-manager |
| 102 | + :language: python |
| 103 | + :copyable: |
| 104 | + |
| 105 | +Run Callbacks After a Transaction |
| 106 | +--------------------------------- |
| 107 | + |
| 108 | +To perform certain actions only if a transaction successfully completes, |
| 109 | +you can use the ``transaction.on_commit()`` function. This function allows you to |
| 110 | +register callbacks that run after a transaction is committed to the |
| 111 | +database. Pass a function, or any callable object, as an argument to |
| 112 | +``on_commit()``. |
| 113 | + |
| 114 | +The following example queries for movies that have a ``genre`` value of |
| 115 | +``["Horror", "Comedy"]`` only after a related database transaction completes: |
| 116 | + |
| 117 | +.. literalinclude:: /includes/interact-data/transactions.py |
| 118 | + :start-after: start-callback |
| 119 | + :end-before: end-callback |
| 120 | + :language: python |
| 121 | + :copyable: |
| 122 | + |
| 123 | +Handle Transaction Errors |
| 124 | +------------------------- |
| 125 | + |
| 126 | +To handle exceptions that occur during a transaction, add error handling |
| 127 | +logic around your atomic code block. If you handle errors inside |
| 128 | +the atomic block, you might obscure these errors from {+framework+}. Since |
| 129 | +{+framework+} uses errors to determine whether to commit or roll |
| 130 | +back a transaction, this can cause unexpected behavior. |
| 131 | + |
| 132 | +If a transaction does not succeed, {+framework+} does not revert any changes made |
| 133 | +to a model's fields. To avoid inconsistencies between your models and database documents, |
| 134 | +you might need to manually restore the original field values. |
| 135 | + |
| 136 | +Example |
| 137 | +~~~~~~~ |
| 138 | + |
| 139 | +The following example includes error handling logic that reverts the modified |
| 140 | +``title`` value of the retrieved document if the database transaction fails: |
| 141 | + |
| 142 | +.. literalinclude:: /includes/interact-data/transactions.py |
| 143 | + :start-after: start-handle-errors |
| 144 | + :end-before: end-handle-errors |
| 145 | + :language: python |
| 146 | + :copyable: |
| 147 | + |
| 148 | +Since the code performs a second database operation based on the |
| 149 | +model's ``title`` value, reverting the change if the transaction errors |
| 150 | +prevents further data inconsistencies. |
| 151 | + |
| 152 | +Additional Information |
| 153 | +---------------------- |
| 154 | + |
| 155 | +To learn more about the {+framework+} transaction API, see `Database Transactions |
| 156 | +<{+django-docs+}/topics/db/transactions>`__ in the {+framework+} documentation. |
0 commit comments