Sophie

Sophie

distrib > Mageia > 6 > armv7hl > by-pkgid > 65530c6176058f9b54858c3b4f6385e6 > files > 942

python-django-doc-1.8.19-1.mga6.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" lang="">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Database transactions &#8212; Django 1.8.19 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.8.19',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="top" title="Django 1.8.19 documentation" href="../../contents.html" />
    <link rel="up" title="Models and databases" href="index.html" />
    <link rel="next" title="Multiple databases" href="multi-db.html" />
    <link rel="prev" title="Performing raw SQL queries" href="sql.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body role="document">

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.8.19 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="sql.html" title="Performing raw SQL queries">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="multi-db.html" title="Multiple databases">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-transactions">
            
  <div class="section" id="s-module-django.db.transaction">
<span id="s-database-transactions"></span><span id="module-django.db.transaction"></span><span id="database-transactions"></span><h1>Database transactions<a class="headerlink" href="#module-django.db.transaction" title="Permalink to this headline">¶</a></h1>
<p>Django gives you a few ways to control how database transactions are managed.</p>
<div class="section" id="s-managing-database-transactions">
<span id="managing-database-transactions"></span><h2>Managing database transactions<a class="headerlink" href="#managing-database-transactions" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-django-s-default-transaction-behavior">
<span id="django-s-default-transaction-behavior"></span><h3>Django&#8217;s default transaction behavior<a class="headerlink" href="#django-s-default-transaction-behavior" title="Permalink to this headline">¶</a></h3>
<p>Django&#8217;s default behavior is to run in autocommit mode. Each query is
immediately committed to the database, unless a transaction is active.
<a class="reference internal" href="#autocommit-details"><span class="std std-ref">See below for details</span></a>.</p>
<p>Django uses transactions or savepoints automatically to guarantee the
integrity of ORM operations that require multiple queries, especially
<a class="reference internal" href="queries.html#topics-db-queries-delete"><span class="std std-ref">delete()</span></a> and <a class="reference internal" href="queries.html#topics-db-queries-update"><span class="std std-ref">update()</span></a> queries.</p>
<p>Django&#8217;s <a class="reference internal" href="../testing/tools.html#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal"><span class="pre">TestCase</span></code></a> class also wraps each test in a
transaction for performance reasons.</p>
</div>
<div class="section" id="s-tying-transactions-to-http-requests">
<span id="s-id1"></span><span id="tying-transactions-to-http-requests"></span><span id="id1"></span><h3>Tying transactions to HTTP requests<a class="headerlink" href="#tying-transactions-to-http-requests" title="Permalink to this headline">¶</a></h3>
<p>A common way to handle transactions on the web is to wrap each request in a
transaction. Set <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><code class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></code></a> to
<code class="docutils literal"><span class="pre">True</span></code> in the configuration of each database for which you want to enable
this behavior.</p>
<p>It works like this. 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.</p>
<p>You may perform subtransactions using savepoints in your view code, typically
with the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> context manager. However, at the end of the view,
either all or none of the changes will be committed.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">While the simplicity of this transaction model is appealing, it also makes it
inefficient when traffic increases. Opening a transaction for every view has
some overhead. The impact on performance depends on the query patterns of your
application and on how well your database handles locking.</p>
</div>
<div class="admonition-per-request-transactions-and-streaming-responses admonition">
<p class="first admonition-title">Per-request transactions and streaming responses</p>
<p>When a view returns a <a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a>, reading
the contents of the response will often execute code to generate the
content. Since the view has already returned, such code runs outside of
the transaction.</p>
<p class="last">Generally speaking, it isn&#8217;t advisable to write to the database while
generating a streaming response, since there&#8217;s no sensible way to handle
errors after starting to send the response.</p>
</div>
<p>In practice, this feature simply wraps every view function in the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a>
decorator described below.</p>
<p>Note that only the execution of your view is enclosed in the transactions.
Middleware runs outside of the transaction, and so does the rendering of
template responses.</p>
<p>When <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><code class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></code></a> is enabled, it&#8217;s
still possible to prevent views from running in a transaction.</p>
<dl class="function">
<dt id="django.db.transaction.non_atomic_requests">
<code class="descname">non_atomic_requests</code>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#non_atomic_requests"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.non_atomic_requests" title="Permalink to this definition">¶</a></dt>
<dd><p>This decorator will negate the effect of <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><code class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></code></a> for a given view:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">transaction</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">non_atomic_requests</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">do_stuff</span><span class="p">()</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">non_atomic_requests</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="s1">&#39;other&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_other_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">do_stuff_on_the_other_database</span><span class="p">()</span>
</pre></div>
</div>
<p>It only works if it&#8217;s applied to the view itself.</p>
</dd></dl>

</div>
<div class="section" id="s-controlling-transactions-explicitly">
<span id="controlling-transactions-explicitly"></span><h3>Controlling transactions explicitly<a class="headerlink" href="#controlling-transactions-explicitly" title="Permalink to this headline">¶</a></h3>
<p>Django provides a single API to control database transactions.</p>
<dl class="function">
<dt id="django.db.transaction.atomic">
<code class="descname">atomic</code>(<em>using=None</em>, <em>savepoint=True</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#atomic"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.atomic" title="Permalink to this definition">¶</a></dt>
<dd><p>Atomicity is the defining property of database transactions. <code class="docutils literal"><span class="pre">atomic</span></code>
allows us to create a block of code within which the atomicity on the
database is guaranteed. If the block of code is successfully completed, the
changes are committed to the database. If there is an exception, the
changes are rolled back.</p>
<p><code class="docutils literal"><span class="pre">atomic</span></code> blocks can be nested. In this case, when an inner block
completes successfully, its effects can still be rolled back if an
exception is raised in the outer block at a later point.</p>
<p><code class="docutils literal"><span class="pre">atomic</span></code> is usable both as a <span class="xref std std-term">decorator</span>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">transaction</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># This code executes inside a transaction.</span>
    <span class="n">do_stuff</span><span class="p">()</span>
</pre></div>
</div>
<p>and as a <span class="xref std std-term">context manager</span>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">transaction</span>

<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># This code executes in autocommit mode (Django&#39;s default).</span>
    <span class="n">do_stuff</span><span class="p">()</span>

    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
        <span class="c1"># This code executes inside a transaction.</span>
        <span class="n">do_more_stuff</span><span class="p">()</span>
</pre></div>
</div>
<p>Wrapping <code class="docutils literal"><span class="pre">atomic</span></code> in a try/except block allows for natural handling of
integrity errors:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">IntegrityError</span><span class="p">,</span> <span class="n">transaction</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">create_parent</span><span class="p">()</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
            <span class="n">generate_relationships</span><span class="p">()</span>
    <span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
        <span class="n">handle_exception</span><span class="p">()</span>

    <span class="n">add_children</span><span class="p">()</span>
</pre></div>
</div>
<p>In this example, even if <code class="docutils literal"><span class="pre">generate_relationships()</span></code> causes a database
error by breaking an integrity constraint, you can execute queries in
<code class="docutils literal"><span class="pre">add_children()</span></code>, and the changes from <code class="docutils literal"><span class="pre">create_parent()</span></code> are still
there. Note that any operations attempted in <code class="docutils literal"><span class="pre">generate_relationships()</span></code>
will already have been rolled back safely when <code class="docutils literal"><span class="pre">handle_exception()</span></code> is
called, so the exception handler can also operate on the database if
necessary.</p>
<div class="admonition-avoid-catching-exceptions-inside-atomic admonition">
<p class="first admonition-title">Avoid catching exceptions inside <code class="docutils literal"><span class="pre">atomic</span></code>!</p>
<p>When exiting an <code class="docutils literal"><span class="pre">atomic</span></code> block, Django looks at whether it&#8217;s exited
normally or with an exception to determine whether to commit or roll
back. If you catch and handle exceptions inside an <code class="docutils literal"><span class="pre">atomic</span></code> block,
you may hide from Django the fact that a problem has happened. This
can result in unexpected behavior.</p>
<p>This is mostly a concern for <a class="reference internal" href="../../ref/exceptions.html#django.db.DatabaseError" title="django.db.DatabaseError"><code class="xref py py-exc docutils literal"><span class="pre">DatabaseError</span></code></a> and its
subclasses such as <a class="reference internal" href="../../ref/exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal"><span class="pre">IntegrityError</span></code></a>. After such an
error, the transaction is broken and Django will perform a rollback at
the end of the <code class="docutils literal"><span class="pre">atomic</span></code> block. If you attempt to run database
queries before the rollback happens, Django will raise a
<a class="reference internal" href="../../ref/exceptions.html#django.db.transaction.TransactionManagementError" title="django.db.transaction.TransactionManagementError"><code class="xref py py-class docutils literal"><span class="pre">TransactionManagementError</span></code></a>. You may
also encounter this behavior when an ORM-related signal handler raises
an exception.</p>
<p>The correct way to catch database errors is around an <code class="docutils literal"><span class="pre">atomic</span></code> block
as shown above. If necessary, add an extra <code class="docutils literal"><span class="pre">atomic</span></code> block for this
purpose. This pattern has another advantage: it delimits explicitly
which operations will be rolled back if an exception occurs.</p>
<p class="last">If you catch exceptions raised by raw SQL queries, Django&#8217;s behavior
is unspecified and database-dependent.</p>
</div>
<p>In order to guarantee atomicity, <code class="docutils literal"><span class="pre">atomic</span></code> disables some APIs. Attempting
to commit, roll back, or change the autocommit state of the database
connection within an <code class="docutils literal"><span class="pre">atomic</span></code> block will raise an exception.</p>
<p><code class="docutils literal"><span class="pre">atomic</span></code> takes a <code class="docutils literal"><span class="pre">using</span></code> argument which should be the name of a
database. If this argument isn&#8217;t provided, Django uses the <code class="docutils literal"><span class="pre">&quot;default&quot;</span></code>
database.</p>
<p>Under the hood, Django&#8217;s transaction management code:</p>
<ul class="simple">
<li>opens a transaction when entering the outermost <code class="docutils literal"><span class="pre">atomic</span></code> block;</li>
<li>creates a savepoint when entering an inner <code class="docutils literal"><span class="pre">atomic</span></code> block;</li>
<li>releases or rolls back to the savepoint when exiting an inner block;</li>
<li>commits or rolls back the transaction when exiting the outermost block.</li>
</ul>
<p>You can disable the creation of savepoints for inner blocks by setting the
<code class="docutils literal"><span class="pre">savepoint</span></code> argument to <code class="docutils literal"><span class="pre">False</span></code>. If an exception occurs, Django will
perform the rollback when exiting the first parent block with a savepoint
if there is one, and the outermost block otherwise. Atomicity is still
guaranteed by the outer transaction. This option should only be used if
the overhead of savepoints is noticeable. It has the drawback of breaking
the error handling described above.</p>
<p>You may use <code class="docutils literal"><span class="pre">atomic</span></code> when autocommit is turned off. It will only use
savepoints, even for the outermost block.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.8.5:</span> <p>Previously the outermost atomic block couldn&#8217;t be declared with
<code class="docutils literal"><span class="pre">savepoint=False</span></code> when autocommit was turned off.</p>
</div>
</dd></dl>

<div class="admonition-performance-considerations admonition">
<p class="first admonition-title">Performance considerations</p>
<p class="last">Open transactions have a performance cost for your database server. To
minimize this overhead, keep your transactions as short as possible. This
is especially important if you&#8217;re using <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> in long-running
processes, outside of Django&#8217;s request / response cycle.</p>
</div>
</div>
</div>
<div class="section" id="s-autocommit">
<span id="autocommit"></span><h2>Autocommit<a class="headerlink" href="#autocommit" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-why-django-uses-autocommit">
<span id="s-autocommit-details"></span><span id="why-django-uses-autocommit"></span><span id="autocommit-details"></span><h3>Why Django uses autocommit<a class="headerlink" href="#why-django-uses-autocommit" title="Permalink to this headline">¶</a></h3>
<p>In the SQL standards, each SQL query starts a transaction, unless one is
already active. Such transactions must then be explicitly committed or rolled
back.</p>
<p>This isn&#8217;t always convenient for application developers. To alleviate this
problem, most databases provide an autocommit mode. When autocommit is turned
on and no transaction is active, each SQL query gets wrapped in its own
transaction. In other words, not only does each such query start a
transaction, but the transaction also gets automatically committed or rolled
back, depending on whether the query succeeded.</p>
<p><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>, the Python Database API Specification v2.0, requires autocommit to
be initially turned off. Django overrides this default and turns autocommit
on.</p>
<p>To avoid this, you can <a class="reference internal" href="#deactivate-transaction-management"><span class="std std-ref">deactivate the transaction management</span></a>, but it isn&#8217;t recommended.</p>
</div>
<div class="section" id="s-deactivating-transaction-management">
<span id="s-deactivate-transaction-management"></span><span id="deactivating-transaction-management"></span><span id="deactivate-transaction-management"></span><h3>Deactivating transaction management<a class="headerlink" href="#deactivating-transaction-management" title="Permalink to this headline">¶</a></h3>
<p>You can totally disable Django&#8217;s transaction management for a given database
by setting <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-AUTOCOMMIT"><code class="xref std std-setting docutils literal"><span class="pre">AUTOCOMMIT</span></code></a> to <code class="docutils literal"><span class="pre">False</span></code> in its
configuration. If you do this, Django won&#8217;t enable autocommit, and won&#8217;t
perform any commits. You&#8217;ll get the regular behavior of the underlying
database library.</p>
<p>This requires you to commit explicitly every transaction, even those started
by Django or by third-party libraries. Thus, this is best used in situations
where you want to run your own transaction-controlling middleware or do
something really strange.</p>
</div>
</div>
<div class="section" id="s-low-level-apis">
<span id="low-level-apis"></span><h2>Low-level APIs<a class="headerlink" href="#low-level-apis" title="Permalink to this headline">¶</a></h2>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Always prefer <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> if possible at all. It accounts for the
idiosyncrasies of each database and prevents invalid operations.</p>
<p class="last">The low level APIs are only useful if you&#8217;re implementing your own
transaction management.</p>
</div>
<div class="section" id="s-managing-autocommit">
<span id="s-id2"></span><span id="managing-autocommit"></span><span id="id2"></span><h3>Autocommit<a class="headerlink" href="#managing-autocommit" title="Permalink to this headline">¶</a></h3>
<p>Django provides a straightforward API in the <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><code class="xref py py-mod docutils literal"><span class="pre">django.db.transaction</span></code></a>
module to manage the autocommit state of each database connection.</p>
<dl class="function">
<dt id="django.db.transaction.get_autocommit">
<code class="descname">get_autocommit</code>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#get_autocommit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.get_autocommit" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.set_autocommit">
<code class="descname">set_autocommit</code>(<em>autocommit</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#set_autocommit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.set_autocommit" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>These functions take a <code class="docutils literal"><span class="pre">using</span></code> argument which should be the name of a
database. If it isn&#8217;t provided, Django uses the <code class="docutils literal"><span class="pre">&quot;default&quot;</span></code> database.</p>
<p>Autocommit is initially turned on. If you turn it off, it&#8217;s your
responsibility to restore it.</p>
<p>Once you turn autocommit off, you get the default behavior of your database
adapter, and Django won&#8217;t help you. Although that behavior is specified in
<span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>, implementations of adapters aren&#8217;t always consistent with one
another. Review the documentation of the adapter you&#8217;re using carefully.</p>
<p>You must ensure that no transaction is active, usually by issuing a
<a class="reference internal" href="#django.db.transaction.commit" title="django.db.transaction.commit"><code class="xref py py-func docutils literal"><span class="pre">commit()</span></code></a> or a <a class="reference internal" href="#django.db.transaction.rollback" title="django.db.transaction.rollback"><code class="xref py py-func docutils literal"><span class="pre">rollback()</span></code></a>, before turning autocommit back on.</p>
<p>Django will refuse to turn autocommit off when an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> block is
active, because that would break atomicity.</p>
</div>
<div class="section" id="s-transactions">
<span id="transactions"></span><h3>Transactions<a class="headerlink" href="#transactions" title="Permalink to this headline">¶</a></h3>
<p>A transaction is an atomic set of database queries. Even if your program
crashes, the database guarantees that either all the changes will be applied,
or none of them.</p>
<p>Django doesn&#8217;t provide an API to start a transaction. The expected way to
start a transaction is to disable autocommit with <a class="reference internal" href="#django.db.transaction.set_autocommit" title="django.db.transaction.set_autocommit"><code class="xref py py-func docutils literal"><span class="pre">set_autocommit()</span></code></a>.</p>
<p>Once you&#8217;re in a transaction, you can choose either to apply the changes
you&#8217;ve performed until this point with <a class="reference internal" href="#django.db.transaction.commit" title="django.db.transaction.commit"><code class="xref py py-func docutils literal"><span class="pre">commit()</span></code></a>, or to cancel them with
<a class="reference internal" href="#django.db.transaction.rollback" title="django.db.transaction.rollback"><code class="xref py py-func docutils literal"><span class="pre">rollback()</span></code></a>. These functions are defined in <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><code class="xref py py-mod docutils literal"><span class="pre">django.db.transaction</span></code></a>.</p>
<dl class="function">
<dt id="django.db.transaction.commit">
<code class="descname">commit</code>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#commit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.commit" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.rollback">
<code class="descname">rollback</code>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.rollback" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>These functions take a <code class="docutils literal"><span class="pre">using</span></code> argument which should be the name of a
database. If it isn&#8217;t provided, Django uses the <code class="docutils literal"><span class="pre">&quot;default&quot;</span></code> database.</p>
<p>Django will refuse to commit or to rollback when an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> block is
active, because that would break atomicity.</p>
</div>
<div class="section" id="s-savepoints">
<span id="s-topics-db-transactions-savepoints"></span><span id="savepoints"></span><span id="topics-db-transactions-savepoints"></span><h3>Savepoints<a class="headerlink" href="#savepoints" title="Permalink to this headline">¶</a></h3>
<p>A savepoint is a marker within a transaction that enables you to roll back
part of a transaction, rather than the full transaction. Savepoints are
available with the SQLite (≥ 3.6.8), PostgreSQL, Oracle and MySQL (when using
the InnoDB storage engine) backends. Other backends provide the savepoint
functions, but they&#8217;re empty operations &#8211; they don&#8217;t actually do anything.</p>
<p>Savepoints aren&#8217;t especially useful if you are using autocommit, the default
behavior of Django. However, once you open a transaction with <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a>,
you build up a series of database operations awaiting a commit or rollback. If
you issue a rollback, the entire transaction is rolled back. Savepoints
provide the ability to perform a fine-grained rollback, rather than the full
rollback that would be performed by <code class="docutils literal"><span class="pre">transaction.rollback()</span></code>.</p>
<p>When the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> decorator is nested, it creates a savepoint to allow
partial commit or rollback. You&#8217;re strongly encouraged to use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a>
rather than the functions described below, but they&#8217;re still part of the
public API, and there&#8217;s no plan to deprecate them.</p>
<p>Each of these functions takes a <code class="docutils literal"><span class="pre">using</span></code> argument which should be the name of
a database for which the behavior applies.  If no <code class="docutils literal"><span class="pre">using</span></code> argument is
provided then the <code class="docutils literal"><span class="pre">&quot;default&quot;</span></code> database is used.</p>
<p>Savepoints are controlled by three functions in <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><code class="xref py py-mod docutils literal"><span class="pre">django.db.transaction</span></code></a>:</p>
<dl class="function">
<dt id="django.db.transaction.savepoint">
<code class="descname">savepoint</code>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#savepoint"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.savepoint" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new savepoint. This marks a point in the transaction that is
known to be in a &#8220;good&#8221; state. Returns the savepoint ID (<code class="docutils literal"><span class="pre">sid</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.savepoint_commit">
<code class="descname">savepoint_commit</code>(<em>sid</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#savepoint_commit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.savepoint_commit" title="Permalink to this definition">¶</a></dt>
<dd><p>Releases savepoint <code class="docutils literal"><span class="pre">sid</span></code>. The changes performed since the savepoint was
created become part of the transaction.</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.savepoint_rollback">
<code class="descname">savepoint_rollback</code>(<em>sid</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#savepoint_rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.savepoint_rollback" title="Permalink to this definition">¶</a></dt>
<dd><p>Rolls back the transaction to savepoint <code class="docutils literal"><span class="pre">sid</span></code>.</p>
</dd></dl>

<p>These functions do nothing if savepoints aren&#8217;t supported or if the database
is in autocommit mode.</p>
<p>In addition, there&#8217;s a utility function:</p>
<dl class="function">
<dt id="django.db.transaction.clean_savepoints">
<code class="descname">clean_savepoints</code>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#clean_savepoints"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.clean_savepoints" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets the counter used to generate unique savepoint IDs.</p>
</dd></dl>

<p>The following example demonstrates the use of savepoints:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">transaction</span>

<span class="c1"># open a transaction</span>
<span class="nd">@transaction</span><span class="o">.</span><span class="n">atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>

    <span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="c1"># transaction now contains a.save()</span>

    <span class="n">sid</span> <span class="o">=</span> <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint</span><span class="p">()</span>

    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="c1"># transaction now contains a.save() and b.save()</span>

    <span class="k">if</span> <span class="n">want_to_keep_b</span><span class="p">:</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_commit</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
        <span class="c1"># open transaction still contains a.save() and b.save()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_rollback</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
        <span class="c1"># open transaction now contains only a.save()</span>
</pre></div>
</div>
<p>Savepoints may be used to recover from a database error by performing a partial
rollback. If you&#8217;re doing this inside an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> block, the entire block
will still be rolled back, because it doesn&#8217;t know you&#8217;ve handled the situation
at a lower level! To prevent this, you can control the rollback behavior with
the following functions.</p>
<dl class="function">
<dt id="django.db.transaction.get_rollback">
<code class="descname">get_rollback</code>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#get_rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.get_rollback" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.set_rollback">
<code class="descname">set_rollback</code>(<em>rollback</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#set_rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.set_rollback" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Setting the rollback flag to <code class="docutils literal"><span class="pre">True</span></code> forces a rollback when exiting the
innermost atomic block. This may be useful to trigger a rollback without
raising an exception.</p>
<p>Setting it to <code class="docutils literal"><span class="pre">False</span></code> prevents such a rollback. Before doing that, make sure
you&#8217;ve rolled back the transaction to a known-good savepoint within the current
atomic block! Otherwise you&#8217;re breaking atomicity and data corruption may
occur.</p>
</div>
</div>
<div class="section" id="s-database-specific-notes">
<span id="database-specific-notes"></span><h2>Database-specific notes<a class="headerlink" href="#database-specific-notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-savepoints-in-sqlite">
<span id="s-id3"></span><span id="savepoints-in-sqlite"></span><span id="id3"></span><h3>Savepoints in SQLite<a class="headerlink" href="#savepoints-in-sqlite" title="Permalink to this headline">¶</a></h3>
<p>While SQLite ≥ 3.6.8 supports savepoints, a flaw in the design of the
<code class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></code> module makes them hardly usable.</p>
<p>When autocommit is enabled, savepoints don&#8217;t make sense. When it&#8217;s disabled,
<code class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></code> commits implicitly before savepoint statements. (In fact, it
commits before any statement other than <code class="docutils literal"><span class="pre">SELECT</span></code>, <code class="docutils literal"><span class="pre">INSERT</span></code>, <code class="docutils literal"><span class="pre">UPDATE</span></code>,
<code class="docutils literal"><span class="pre">DELETE</span></code> and <code class="docutils literal"><span class="pre">REPLACE</span></code>.) This bug has two consequences:</p>
<ul class="simple">
<li>The low level APIs for savepoints are only usable inside a transaction ie.
inside an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> block.</li>
<li>It&#8217;s impossible to use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> when autocommit is turned off.</li>
</ul>
</div>
<div class="section" id="s-transactions-in-mysql">
<span id="transactions-in-mysql"></span><h3>Transactions in MySQL<a class="headerlink" href="#transactions-in-mysql" title="Permalink to this headline">¶</a></h3>
<p>If you&#8217;re using MySQL, your tables may or may not support transactions; it
depends on your MySQL version and the table types you&#8217;re using. (By
&#8220;table types,&#8221; we mean something like &#8220;InnoDB&#8221; or &#8220;MyISAM&#8221;.) MySQL transaction
peculiarities are outside the scope of this article, but the MySQL site has
<a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/sql-syntax-transactions.html">information on MySQL transactions</a>.</p>
<p>If your MySQL setup does <em>not</em> support transactions, then Django will always
function in autocommit mode: statements will be executed and committed as soon
as they&#8217;re called. If your MySQL setup <em>does</em> support transactions, Django
will handle transactions as explained in this document.</p>
</div>
<div class="section" id="s-handling-exceptions-within-postgresql-transactions">
<span id="handling-exceptions-within-postgresql-transactions"></span><h3>Handling exceptions within PostgreSQL transactions<a class="headerlink" href="#handling-exceptions-within-postgresql-transactions" title="Permalink to this headline">¶</a></h3>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This section is relevant only if you&#8217;re implementing your own transaction
management. This problem cannot occur in Django&#8217;s default mode and
<a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal"><span class="pre">atomic()</span></code></a> handles it automatically.</p>
</div>
<p>Inside a transaction, when a call to a PostgreSQL cursor raises an exception
(typically <code class="docutils literal"><span class="pre">IntegrityError</span></code>), all subsequent SQL in the same transaction
will fail with the error &#8220;current transaction is aborted, queries ignored
until end of transaction block&#8221;. Whilst simple use of <code class="docutils literal"><span class="pre">save()</span></code> is unlikely
to raise an exception in PostgreSQL, there are more advanced usage patterns
which might, such as saving objects with unique fields, saving using the
force_insert/force_update flag, or invoking custom SQL.</p>
<p>There are several ways to recover from this sort of error.</p>
<div class="section" id="s-transaction-rollback">
<span id="transaction-rollback"></span><h4>Transaction rollback<a class="headerlink" href="#transaction-rollback" title="Permalink to this headline">¶</a></h4>
<p>The first option is to roll back the entire transaction. For example:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, but may be undone by transaction rollback</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Could throw exception</span>
<span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, but a.save() may have been undone</span>
</pre></div>
</div>
<p>Calling <code class="docutils literal"><span class="pre">transaction.rollback()</span></code> rolls back the entire transaction. Any
uncommitted database operations will be lost. In this example, the changes
made by <code class="docutils literal"><span class="pre">a.save()</span></code> would be lost, even though that operation raised no error
itself.</p>
</div>
<div class="section" id="s-savepoint-rollback">
<span id="savepoint-rollback"></span><h4>Savepoint rollback<a class="headerlink" href="#savepoint-rollback" title="Permalink to this headline">¶</a></h4>
<p>You can use <a class="reference internal" href="#topics-db-transactions-savepoints"><span class="std std-ref">savepoints</span></a> to control
the extent of a rollback. Before performing a database operation that could
fail, you can set or update the savepoint; that way, if the operation fails,
you can roll back the single offending operation, rather than the entire
transaction. For example:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, and never undone by savepoint rollback</span>
<span class="n">sid</span> <span class="o">=</span> <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Could throw exception</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_commit</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
<span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_rollback</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
<span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, and a.save() is never undone</span>
</pre></div>
</div>
<p>In this example, <code class="docutils literal"><span class="pre">a.save()</span></code> will not be undone in the case where
<code class="docutils literal"><span class="pre">b.save()</span></code> raises an exception.</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Database transactions</a><ul>
<li><a class="reference internal" href="#managing-database-transactions">Managing database transactions</a><ul>
<li><a class="reference internal" href="#django-s-default-transaction-behavior">Django&#8217;s default transaction behavior</a></li>
<li><a class="reference internal" href="#tying-transactions-to-http-requests">Tying transactions to HTTP requests</a></li>
<li><a class="reference internal" href="#controlling-transactions-explicitly">Controlling transactions explicitly</a></li>
</ul>
</li>
<li><a class="reference internal" href="#autocommit">Autocommit</a><ul>
<li><a class="reference internal" href="#why-django-uses-autocommit">Why Django uses autocommit</a></li>
<li><a class="reference internal" href="#deactivating-transaction-management">Deactivating transaction management</a></li>
</ul>
</li>
<li><a class="reference internal" href="#low-level-apis">Low-level APIs</a><ul>
<li><a class="reference internal" href="#managing-autocommit">Autocommit</a></li>
<li><a class="reference internal" href="#transactions">Transactions</a></li>
<li><a class="reference internal" href="#savepoints">Savepoints</a></li>
</ul>
</li>
<li><a class="reference internal" href="#database-specific-notes">Database-specific notes</a><ul>
<li><a class="reference internal" href="#savepoints-in-sqlite">Savepoints in SQLite</a></li>
<li><a class="reference internal" href="#transactions-in-mysql">Transactions in MySQL</a></li>
<li><a class="reference internal" href="#handling-exceptions-within-postgresql-transactions">Handling exceptions within PostgreSQL transactions</a><ul>
<li><a class="reference internal" href="#transaction-rollback">Transaction rollback</a></li>
<li><a class="reference internal" href="#savepoint-rollback">Savepoint rollback</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="sql.html">Performing raw SQL queries</a></li>
    
    
      <li>Next: <a href="multi-db.html">Multiple databases</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.8.19 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Models and databases</a>
        
        <ul><li>Database transactions</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/db/transactions.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Mar 10, 2018</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="sql.html" title="Performing raw SQL queries">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="multi-db.html" title="Multiple databases">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>