{"title":"データベースのトランザクション","version":"4.2","locale":"ja","docname":"topics/db/transactions","url":"/ja/4.2/topics/db/transactions/","canonical":"https://djangodocs.dev/ja/4.2/topics/db/transactions/","summary":"Django では、データベースのトランザクションをコントロールする方法が提供されています。 データベースのトランザクションを管理する Link to this heading # Django のデフォルトのトランザクションの動作 Link to this heading # Django…","html":"<span id=\"database-transactions\"></span><h1>データベースのトランザクション<a class=\"heading-anchor\" href=\"#module-django.db.transaction\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>Django では、データベースのトランザクションをコントロールする方法が提供されています。</p>\n<section id=\"managing-database-transactions\">\n<h2>データベースのトランザクションを管理する<a class=\"heading-anchor\" href=\"#managing-database-transactions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"django-s-default-transaction-behavior\">\n<h3>Django のデフォルトのトランザクションの動作<a class=\"heading-anchor\" href=\"#django-s-default-transaction-behavior\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django のデフォルトの動作は、オートコミットモードで実行することです。トランザクションがアクティブでない限り、各クエリは即座にデータベースにコミットされます。<a class=\"reference internal\" href=\"#autocommit-details\"><span class=\"std std-ref\">詳しくは下記を参照してください</span></a>。</p>\n<p>Django は、自動的にトランザクションやセーブポイントを使い、特に <a class=\"reference internal\" href=\"/ja/4.2/topics/db/queries/#topics-db-queries-delete\"><span class=\"std std-ref\">delete()</span></a> と <a class=\"reference internal\" href=\"/ja/4.2/topics/db/queries/#topics-db-queries-update\"><span class=\"std std-ref\">update()</span></a> クエリにおいて、複数のクエリを要求する ORM 操作の信頼性を担保します。</p>\n<p>Django の <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TestCase</span></code></a> クラスは、パフォーマンス向上のため、各テストをトランザクションでラップします。</p>\n</section>\n<section id=\"tying-transactions-to-http-requests\">\n<span id=\"id1\"></span><h3>HTTP リクエストにトランザクションを結びつける<a class=\"heading-anchor\" href=\"#tying-transactions-to-http-requests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>ウェブ上でトランザクションを扱う一般的な方法は、各リクエストをトランザクションでラップすることです。この動作を有効化したい各データベースの設定で、<a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-ATOMIC_REQUESTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ATOMIC_REQUESTS</span></code></a> を <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code> にセットしてください。</p>\n<p>これは、次のように動作します。まず、ビュー関数を呼び出す前に、Django はトランザクションを開始します。レスポンスが問題なく生成された場合は、Django はトランザクションをコミットします。もしビューが例外を生成した場合は、Django はトランザクションをロールバックします。</p>\n<p>ビューのコード (通常は <a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> コンテキストマネージャー) の中で、セーブポイントを使ったサブトランザクションを扱うことができます。ただし、ビューの最後では、すべての変更がコミットされるか、何もコミットされないかのどちらかです。</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>このトランザクションモデルは簡潔ではありますが、トラフィックが増加するときには非効率となります。全てのビューでトランザクションを扱うとオーバーヘッドが増加します。パフォーマンスへの影響は、アプリケーションのクエリパターンと、どれだけうまくデータベースがロッキングを扱うかに依存します。</p>\n</aside>\n<aside class=\"admonition-per-request-transactions-and-streaming-responses admonition\">\n<p class=\"admonition-title\">リクエストごとのトランザクションとストリーミングレスポンス</p>\n<p>ビューが <a class=\"reference internal\" href=\"/ja/4.2/ref/request-response/#django.http.StreamingHttpResponse\" title=\"django.http.StreamingHttpResponse\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">StreamingHttpResponse</span></code></a> を返すとき、レスポンスの内容読み出しが内容を生成するためのコードを実行することがあります。ビューはすでに返されているので、このコードはトランザクションの外で走ります。</p>\n<p>一般的に言って、ストリーミングレスポンスが生成されている間はデータベースに書き込みすることは推奨されません。レスポンスを送信開始した後にエラーを扱う適切な方法が存在しないからです。</p>\n</aside>\n<p>In practice, this feature 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 notranslate\"><span class=\"pre\">atomic()</span></code></a>\ndecorator described below.</p>\n<p>あなたのビューの実行だけがトランザクションで閉じられることに注意してください。ミドルウェアはトランザクションの外で実行し、テンプレートレスポンスのレンダリングを実行します。</p>\n<p><a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-ATOMIC_REQUESTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ATOMIC_REQUESTS</span></code></a> が有効な場合、ビューがトランザクション内で実行するのを防ぐことができます。</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.non_atomic_requests\">\n<span class=\"sig-name descname\"><span class=\"pre\">non_atomic_requests</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.non_atomic_requests\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>このデコレータは、与えられたビューのために <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-ATOMIC_REQUESTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ATOMIC_REQUESTS</span></code></a> を無効化します。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">transaction</span>\n\n\n<span class=\"nd\">@transaction</span><span class=\"o\">.</span><span class=\"n\">non_atomic_requests</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">do_stuff</span><span class=\"p\">()</span>\n\n\n<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=\"s2\">&quot;other&quot;</span><span class=\"p\">)</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_other_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">do_stuff_on_the_other_database</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>ビュー自身に適用される場合にのみ作動します。</p>\n</dd></dl>\n\n</section>\n<section id=\"controlling-transactions-explicitly\">\n<h3>明示的にトランザクションをコントロールする<a class=\"heading-anchor\" href=\"#controlling-transactions-explicitly\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django は、データベーストランザクションをコントロールするための一つの API を提供しています。</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.atomic\">\n<span class=\"sig-name descname\"><span class=\"pre\">atomic</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">savepoint</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">True</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">durable</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">False</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.atomic\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Atomicityは、データベーストランザクションの定義プロパティです。<code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> は、データベースの atomicity が保証されるコードブロックを作成することを可能にします。 コードブロックが正常に完了すると、変更はデータベースにコミットされます。 例外がある場合、変更はロールバックされます。</p>\n<p><code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> のブロックはネスト可能です。この場合、内側のブロックが成功裏に完了しても、その効果は後で外側のブロックで例外が発生した場合にロールバック可能となっています。</p>\n<p>It is sometimes useful to ensure an <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> block is always the\noutermost <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> block, ensuring that any database changes are\ncommitted when the block is exited without errors. This is known as\ndurability and can be achieved by setting <code class=\"docutils literal notranslate\"><span class=\"pre\">durable=True</span></code>. If the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> block is nested within another it raises a <code class=\"docutils literal notranslate\"><span class=\"pre\">RuntimeError</span></code>.</p>\n<p><code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> は、<a class=\"reference external\" href=\"https://docs.python.org/3/glossary.html#term-decorator\" title=\"(in Python v3.14)\"><span class=\"xref std std-term\">decorator</span></a> として使用することも:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">transaction</span>\n\n\n<span class=\"nd\">@transaction</span><span class=\"o\">.</span><span class=\"n\">atomic</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">viewfunc</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"c1\"># This code executes inside a transaction.</span>\n    <span class=\"n\">do_stuff</span><span class=\"p\">()</span>\n</code></pre></div>\n<p><a class=\"reference external\" href=\"https://docs.python.org/3/glossary.html#term-context-manager\" title=\"(in Python v3.14)\"><span class=\"xref std std-term\">context manager</span></a> として使用することも可能です:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">transaction</span>\n\n\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">viewfunc</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"c1\"># This code executes in autocommit mode (Django&#39;s default).</span>\n    <span class=\"n\">do_stuff</span><span class=\"p\">()</span>\n\n    <span class=\"k\">with</span> <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">atomic</span><span class=\"p\">():</span>\n        <span class=\"c1\"># This code executes inside a transaction.</span>\n        <span class=\"n\">do_more_stuff</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>try/except ブロック内で <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> をラップすると、integrity error を自然な形で処理できます:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">IntegrityError</span><span class=\"p\">,</span> <span class=\"n\">transaction</span>\n\n\n<span class=\"nd\">@transaction</span><span class=\"o\">.</span><span class=\"n\">atomic</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">viewfunc</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">create_parent</span><span class=\"p\">()</span>\n\n    <span class=\"k\">try</span><span class=\"p\">:</span>\n        <span class=\"k\">with</span> <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">atomic</span><span class=\"p\">():</span>\n            <span class=\"n\">generate_relationships</span><span class=\"p\">()</span>\n    <span class=\"k\">except</span> <span class=\"n\">IntegrityError</span><span class=\"p\">:</span>\n        <span class=\"n\">handle_exception</span><span class=\"p\">()</span>\n\n    <span class=\"n\">add_children</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>In this example, even if <code class=\"docutils literal notranslate\"><span class=\"pre\">generate_relationships()</span></code> causes a database\nerror by breaking an integrity constraint, you can execute queries in\n<code class=\"docutils literal notranslate\"><span class=\"pre\">add_children()</span></code>, and the changes from <code class=\"docutils literal notranslate\"><span class=\"pre\">create_parent()</span></code> are still\nthere and bound to the same transaction. Note that any operations attempted\nin <code class=\"docutils literal notranslate\"><span class=\"pre\">generate_relationships()</span></code> will already have been rolled back safely\nwhen <code class=\"docutils literal notranslate\"><span class=\"pre\">handle_exception()</span></code> is called, so the exception handler can also\noperate on the database if necessary.</p>\n<aside class=\"admonition-avoid-catching-exceptions-inside-atomic admonition\">\n<p class=\"admonition-title\"><code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> の内部で例外をキャッチしない!</p>\n<p><code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> ブロックの処理を終える際、Django は通常の終了なのか例外を伴うのかを見て、コミットするかロールバックするかを決定します。<code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> ブロック内で例外をキャッチしてハンドする場合、Django に対して問題が発生したことを隠すことになります。これは予期しない動作の原因となります。</p>\n<p>この挙動は、<a class=\"reference internal\" href=\"/ja/4.2/ref/exceptions/#django.db.DatabaseError\" title=\"django.db.DatabaseError\"><code class=\"xref py py-exc docutils literal notranslate\"><span class=\"pre\">DatabaseError</span></code></a> およびそのサブクラス　(<a class=\"reference internal\" href=\"/ja/4.2/ref/exceptions/#django.db.IntegrityError\" title=\"django.db.IntegrityError\"><code class=\"xref py py-exc docutils literal notranslate\"><span class=\"pre\">IntegrityError</span></code></a> など) に対する懸念となります。こうしたエラーが起きた場合、Djangoは <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> ブロックの最後にロー路バックを実施します。ロールバックが発生する前にデータベースクエリを実行しようとすると、Django は <a class=\"reference internal\" href=\"/ja/4.2/ref/exceptions/#django.db.transaction.TransactionManagementError\" title=\"django.db.transaction.TransactionManagementError\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TransactionManagementError</span></code></a> を送出します。ORM 関連のシグナルハンドラが例外を送出した際にも同様の挙動となります。</p>\n<p>データベースエラーをキャッチする正しい方法は、上記で示した通りの <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> ブロックです。必要に応じてさらに <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> ブロックを追加してください。このパターンはもう一つのメリットがあります: 例外が発生した場合にどの操作がロールバックされるかを限定できることです。</p>\n<p>素の SQL クエリによって発生した例外をキャッチした場合、Django の挙動は決まっておらず、データベースに依存します。</p>\n</aside>\n<aside class=\"admonition-you-may-need-to-manually-revert-app-state-when-rolling-back-a-transaction admonition\">\n<p class=\"admonition-title\">You may need to manually revert app state when rolling back a transaction.</p>\n<p>The values of a model's fields won't be reverted when a transaction\nrollback happens. This could lead to an inconsistent model state unless\nyou manually restore the original field values.</p>\n<p>For example, given <code class=\"docutils literal notranslate\"><span class=\"pre\">MyModel</span></code> with an <code class=\"docutils literal notranslate\"><span class=\"pre\">active</span></code> field, this snippet\nensures that the <code class=\"docutils literal notranslate\"><span class=\"pre\">if</span> <span class=\"pre\">obj.active</span></code> check at the end uses the correct\nvalue if updating <code class=\"docutils literal notranslate\"><span class=\"pre\">active</span></code> to <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code> fails in the transaction:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">DatabaseError</span><span class=\"p\">,</span> <span class=\"n\">transaction</span>\n\n<span class=\"n\">obj</span> <span class=\"o\">=</span> <span class=\"n\">MyModel</span><span class=\"p\">(</span><span class=\"n\">active</span><span class=\"o\">=</span><span class=\"kc\">False</span><span class=\"p\">)</span>\n<span class=\"n\">obj</span><span class=\"o\">.</span><span class=\"n\">active</span> <span class=\"o\">=</span> <span class=\"kc\">True</span>\n<span class=\"k\">try</span><span class=\"p\">:</span>\n    <span class=\"k\">with</span> <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">atomic</span><span class=\"p\">():</span>\n        <span class=\"n\">obj</span><span class=\"o\">.</span><span class=\"n\">save</span><span class=\"p\">()</span>\n<span class=\"k\">except</span> <span class=\"n\">DatabaseError</span><span class=\"p\">:</span>\n    <span class=\"n\">obj</span><span class=\"o\">.</span><span class=\"n\">active</span> <span class=\"o\">=</span> <span class=\"kc\">False</span>\n\n<span class=\"k\">if</span> <span class=\"n\">obj</span><span class=\"o\">.</span><span class=\"n\">active</span><span class=\"p\">:</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>This also applies to any other mechanism that may hold app state, such\nas caching or global variables. For example, if the code proactively\nupdates data in the cache after saving an object, it's recommended to\nuse <a class=\"reference internal\" href=\"#performing-actions-after-commit\"><span class=\"std std-ref\">transaction.on_commit()</span></a>\ninstead, to defer cache alterations until the transaction is actually\ncommitted.</p>\n</aside>\n<p>In order to guarantee atomicity, <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> disables some APIs. Attempting\nto commit, roll back, or change the autocommit state of the database\nconnection within an <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> block will raise an exception.</p>\n<p><code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> takes a <code class=\"docutils literal notranslate\"><span class=\"pre\">using</span></code> argument which should be the name of a\ndatabase. If this argument isn't provided, Django uses the <code class=\"docutils literal notranslate\"><span class=\"pre\">&quot;default&quot;</span></code>\ndatabase.</p>\n<p>Under the hood, Django's transaction management code:</p>\n<ul class=\"simple\">\n<li><p>opens a transaction when entering the outermost <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> block;</p></li>\n<li><p>creates a savepoint when entering an inner <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> block;</p></li>\n<li><p>releases or rolls back to the savepoint when exiting an inner block;</p></li>\n<li><p>commits or rolls back the transaction when exiting the outermost block.</p></li>\n</ul>\n<p>You can disable the creation of savepoints for inner blocks by setting the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">savepoint</span></code> argument to <code class=\"docutils literal notranslate\"><span class=\"pre\">False</span></code>. If an exception occurs, Django will\nperform the rollback when exiting the first parent block with a savepoint\nif there is one, and the outermost block otherwise. Atomicity is still\nguaranteed by the outer transaction. This option should only be used if\nthe overhead of savepoints is noticeable. It has the drawback of breaking\nthe error handling described above.</p>\n<p>You may use <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> when autocommit is turned off. It will only use\nsavepoints, even for the outermost block.</p>\n</dd></dl>\n\n<aside class=\"admonition-performance-considerations admonition\">\n<p class=\"admonition-title\">Performance considerations</p>\n<p>Open transactions have a performance cost for your database server. To\nminimize this overhead, keep your transactions as short as possible. This\nis especially important if you're using <a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> in long-running\nprocesses, outside of Django's request / response cycle.</p>\n</aside>\n<aside class=\"version-note version-changed\" data-version=\"4.1\">\n<p class=\"version-note-title\">Changed in Django 4.1</p><p>In older versions, the durability check was disabled in\n<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">django.test.TestCase</span></code></a>.</p>\n</aside>\n</section>\n</section>\n<section id=\"autocommit\">\n<h2>自動コミット<a class=\"heading-anchor\" href=\"#autocommit\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"why-django-uses-autocommit\">\n<span id=\"autocommit-details\"></span><h3>なぜ Django は自動コミットを使うのか<a class=\"heading-anchor\" href=\"#why-django-uses-autocommit\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>In the SQL standards, each SQL query starts a transaction, unless one is\nalready active. Such transactions must then be explicitly committed or rolled\nback.</p>\n<p>This isn't always convenient for application developers. To alleviate this\nproblem, most databases provide an autocommit mode. When autocommit is turned\non and no transaction is active, each SQL query gets wrapped in its own\ntransaction. In other words, not only does each such query start a\ntransaction, but the transaction also gets automatically committed or rolled\nback, depending on whether the query succeeded.</p>\n<p><span class=\"target\" id=\"index-0\"></span><a class=\"pep reference external\" href=\"https://peps.python.org/pep-0249/\"><strong>PEP 249</strong></a>, the Python Database API Specification v2.0, requires autocommit to\nbe initially turned off. Django overrides this default and turns autocommit\non.</p>\n<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't recommended.</p>\n</section>\n<section id=\"deactivating-transaction-management\">\n<span id=\"deactivate-transaction-management\"></span><h3>Deactivating transaction management<a class=\"heading-anchor\" href=\"#deactivating-transaction-management\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>You can totally disable Django's transaction management for a given database\nby setting <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-AUTOCOMMIT\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">AUTOCOMMIT</span></code></a> to <code class=\"docutils literal notranslate\"><span class=\"pre\">False</span></code> in its\nconfiguration. If you do this, Django won't enable autocommit, and won't\nperform any commits. You'll get the regular behavior of the underlying\ndatabase library.</p>\n<p>This requires you to commit explicitly every transaction, even those started\nby Django or by third-party libraries. Thus, this is best used in situations\nwhere you want to run your own transaction-controlling middleware or do\nsomething really strange.</p>\n</section>\n</section>\n<section id=\"performing-actions-after-commit\">\n<span id=\"id2\"></span><h2>Performing actions after commit<a class=\"heading-anchor\" href=\"#performing-actions-after-commit\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Sometimes you need to perform an action related to the current database\ntransaction, but only if the transaction successfully commits. Examples might\ninclude a background task, an email notification, or a cache invalidation.</p>\n<p><a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a> allows you to register callbacks that will be executed after\nthe open transaction is successfully committed:</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.on_commit\">\n<span class=\"sig-name descname\"><span class=\"pre\">on_commit</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">func</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">robust</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">False</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.on_commit\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Pass a function, or any callable, to <a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">transaction</span>\n\n\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">send_welcome_email</span><span class=\"p\">():</span>\n    <span class=\"o\">...</span>\n\n\n<span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">on_commit</span><span class=\"p\">(</span><span class=\"n\">send_welcome_email</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>Callbacks will not be passed any arguments, but you can bind them with\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/functools.html#functools.partial\" title=\"(in Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">functools.partial()</span></code></a>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">functools</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">partial</span>\n\n<span class=\"k\">for</span> <span class=\"n\">user</span> <span class=\"ow\">in</span> <span class=\"n\">users</span><span class=\"p\">:</span>\n    <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">on_commit</span><span class=\"p\">(</span><span class=\"n\">partial</span><span class=\"p\">(</span><span class=\"n\">send_invite_email</span><span class=\"p\">,</span> <span class=\"n\">user</span><span class=\"o\">=</span><span class=\"n\">user</span><span class=\"p\">))</span>\n</code></pre></div>\n<p>Callbacks are called after the open transaction is successfully committed. If\nthe transaction is instead rolled back (typically when an unhandled exception\nis raised in an <a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> block), the callback will be discarded, and\nnever called.</p>\n<p>If you call <code class=\"docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code> while there isn't an open transaction,\nthe callback will be executed immediately.</p>\n<p>It's sometimes useful to register callbacks that can fail. Passing\n<code class=\"docutils literal notranslate\"><span class=\"pre\">robust=True</span></code> allows the next callbacks to be executed even if the current\none throws an exception. All errors derived from Python's <code class=\"docutils literal notranslate\"><span class=\"pre\">Exception</span></code> class\nare caught and logged to the <code class=\"docutils literal notranslate\"><span class=\"pre\">django.db.backends.base</span></code> logger.</p>\n<p>You can use <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase.captureOnCommitCallbacks\" title=\"django.test.TestCase.captureOnCommitCallbacks\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">TestCase.captureOnCommitCallbacks()</span></code></a> to test callbacks\nregistered with <a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a>.</p>\n<aside class=\"version-note version-changed\" data-version=\"4.2\">\n<p class=\"version-note-title\">Changed in Django 4.2</p><p>The <code class=\"docutils literal notranslate\"><span class=\"pre\">robust</span></code> argument was added.</p>\n</aside>\n<section id=\"savepoints\">\n<h3>Savepoints<a class=\"heading-anchor\" href=\"#savepoints\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Savepoints (i.e. nested <a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> blocks) are handled correctly. That is,\nan <a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a> callable registered after a savepoint (in a nested\n<a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> block) will be called after the outer transaction is committed,\nbut not if a rollback to that savepoint or any previous savepoint occurred\nduring the transaction:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><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\"># Outer atomic, start a new transaction</span>\n    <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">on_commit</span><span class=\"p\">(</span><span class=\"n\">foo</span><span class=\"p\">)</span>\n\n    <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\"># Inner atomic block, create a savepoint</span>\n        <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">on_commit</span><span class=\"p\">(</span><span class=\"n\">bar</span><span class=\"p\">)</span>\n\n<span class=\"c1\"># foo() and then bar() will be called when leaving the outermost block</span>\n</code></pre></div>\n<p>On the other hand, when a savepoint is rolled back (due to an exception being\nraised), the inner callable will not be called:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><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\"># Outer atomic, start a new transaction</span>\n    <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">on_commit</span><span class=\"p\">(</span><span class=\"n\">foo</span><span class=\"p\">)</span>\n\n    <span class=\"k\">try</span><span class=\"p\">:</span>\n        <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\"># Inner atomic block, create a savepoint</span>\n            <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">on_commit</span><span class=\"p\">(</span><span class=\"n\">bar</span><span class=\"p\">)</span>\n            <span class=\"k\">raise</span> <span class=\"n\">SomeError</span><span class=\"p\">()</span>  <span class=\"c1\"># Raising an exception - abort the savepoint</span>\n    <span class=\"k\">except</span> <span class=\"n\">SomeError</span><span class=\"p\">:</span>\n        <span class=\"k\">pass</span>\n\n<span class=\"c1\"># foo() will be called, but not bar()</span>\n</code></pre></div>\n</section>\n<section id=\"order-of-execution\">\n<h3>Order of execution<a class=\"heading-anchor\" href=\"#order-of-execution\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>On-commit functions for a given transaction are executed in the order they were\nregistered.</p>\n</section>\n<section id=\"exception-handling\">\n<h3>Exception handling<a class=\"heading-anchor\" href=\"#exception-handling\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If one on-commit function registered with <code class=\"docutils literal notranslate\"><span class=\"pre\">robust=False</span></code> within a given\ntransaction raises an uncaught exception, no later registered functions in that\nsame transaction will run. This is the same behavior as if you'd executed the\nfunctions sequentially yourself without <a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a>.</p>\n<aside class=\"version-note version-changed\" data-version=\"4.2\">\n<p class=\"version-note-title\">Changed in Django 4.2</p><p>The <code class=\"docutils literal notranslate\"><span class=\"pre\">robust</span></code> argument was added.</p>\n</aside>\n</section>\n<section id=\"timing-of-execution\">\n<h3>Timing of execution<a class=\"heading-anchor\" href=\"#timing-of-execution\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Your callbacks are executed <em>after</em> a successful commit, so a failure in a\ncallback will not cause the transaction to roll back. They are executed\nconditionally upon the success of the transaction, but they are not <em>part</em> of\nthe transaction. For the intended use cases (mail notifications, background\ntasks, etc.), this should be fine. If it's not (if your follow-up action is so\ncritical that its failure should mean the failure of the transaction itself),\nthen you don't want to use the <a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a> hook. Instead, you may want\n<a class=\"reference external\" href=\"https://en.wikipedia.org/wiki/Two-phase_commit_protocol\">two-phase commit</a> such as the <a class=\"reference external\" href=\"https://www.psycopg.org/psycopg3/docs/basic/transactions.html#two-phase-commit\" title=\"(in psycopg)\"><span class=\"xref std std-ref\">psycopg Two-Phase Commit protocol support</span></a> and the <span class=\"target\" id=\"index-1\"></span><a class=\"pep reference external\" href=\"https://peps.python.org/pep-0249/#optional-two-phase-commit-extensions\"><strong>optional Two-Phase Commit Extensions\nin the Python DB-API specification</strong></a>.</p>\n<p>Callbacks are not run until autocommit is restored on the connection following\nthe commit (because otherwise any queries done in a callback would open an\nimplicit transaction, preventing the connection from going back into autocommit\nmode).</p>\n<p>When in autocommit mode and outside of an <a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> block, the function\nwill run immediately, not on commit.</p>\n<p>On-commit functions only work with <a class=\"reference internal\" href=\"#managing-autocommit\"><span class=\"std std-ref\">autocommit mode</span></a>\nand the <a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> (or <a class=\"reference internal\" href=\"/ja/4.2/ref/settings/#std-setting-DATABASE-ATOMIC_REQUESTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ATOMIC_REQUESTS</span></code></a>) transaction API. Calling <a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a> when\nautocommit is disabled and you are not within an atomic block will result in an\nerror.</p>\n</section>\n<section id=\"use-in-tests\">\n<h3>Use in tests<a class=\"heading-anchor\" href=\"#use-in-tests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django's <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TestCase</span></code></a> class wraps each test in a transaction\nand rolls back that transaction after each test, in order to provide test\nisolation. This means that no transaction is ever actually committed, thus your\n<a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a> callbacks will never be run.</p>\n<p>You can overcome this limitation by using\n<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase.captureOnCommitCallbacks\" title=\"django.test.TestCase.captureOnCommitCallbacks\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">TestCase.captureOnCommitCallbacks()</span></code></a>. This captures your\n<a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a> callbacks in a list, allowing you to make assertions on them,\nor emulate the transaction committing by calling them.</p>\n<p>Another way to overcome the limitation is to use\n<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TransactionTestCase</span></code></a> instead of\n<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TestCase</span></code></a>. This will mean your transactions are committed,\nand the callbacks will run. However\n<a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TransactionTestCase\" title=\"django.test.TransactionTestCase\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TransactionTestCase</span></code></a> flushes the database between tests,\nwhich is significantly slower than <a class=\"reference internal\" href=\"/ja/4.2/topics/testing/tools/#django.test.TestCase\" title=\"django.test.TestCase\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">TestCase</span></code></a>'s isolation.</p>\n</section>\n<section id=\"why-no-rollback-hook\">\n<h3>Why no rollback hook?<a class=\"heading-anchor\" href=\"#why-no-rollback-hook\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>A rollback hook is harder to implement robustly than a commit hook, since a\nvariety of things can cause an implicit rollback.</p>\n<p>For instance, if your database connection is dropped because your process was\nkilled without a chance to shut down gracefully, your rollback hook will never\nrun.</p>\n<p>But there is a solution: instead of doing something during the atomic block\n(transaction) and then undoing it if the transaction fails, use\n<a class=\"reference internal\" href=\"#django.db.transaction.on_commit\" title=\"django.db.transaction.on_commit\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">on_commit()</span></code></a> to delay doing it in the first place until after the\ntransaction succeeds. It's a lot easier to undo something you never did in the\nfirst place!</p>\n</section>\n</section>\n<section id=\"low-level-apis\">\n<h2>Low-level APIs<a class=\"heading-anchor\" href=\"#low-level-apis\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<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 notranslate\"><span class=\"pre\">atomic()</span></code></a> if possible at all. It accounts for the\nidiosyncrasies of each database and prevents invalid operations.</p>\n<p>The low level APIs are only useful if you're implementing your own\ntransaction management.</p>\n</aside>\n<section id=\"managing-autocommit\">\n<span id=\"id3\"></span><h3>自動コミット<a class=\"heading-anchor\" href=\"#managing-autocommit\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django provides an API in the <a class=\"reference internal\" href=\"#module-django.db.transaction\" title=\"django.db.transaction\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">django.db.transaction</span></code></a> module to manage the\nautocommit state of each database connection.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.get_autocommit\">\n<span class=\"sig-name descname\"><span class=\"pre\">get_autocommit</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.get_autocommit\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.set_autocommit\">\n<span class=\"sig-name descname\"><span class=\"pre\">set_autocommit</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">autocommit</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.set_autocommit\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>These functions take a <code class=\"docutils literal notranslate\"><span class=\"pre\">using</span></code> argument which should be the name of a\ndatabase. If it isn't provided, Django uses the <code class=\"docutils literal notranslate\"><span class=\"pre\">&quot;default&quot;</span></code> database.</p>\n<p>Autocommit is initially turned on. If you turn it off, it's your\nresponsibility to restore it.</p>\n<p>Once you turn autocommit off, you get the default behavior of your database\nadapter, and Django won't help you. Although that behavior is specified in\n<span class=\"target\" id=\"index-2\"></span><a class=\"pep reference external\" href=\"https://peps.python.org/pep-0249/\"><strong>PEP 249</strong></a>, implementations of adapters aren't always consistent with one\nanother. Review the documentation of the adapter you're using carefully.</p>\n<p>You must ensure that no transaction is active, usually by issuing a\n<a class=\"reference internal\" href=\"#django.db.transaction.commit\" title=\"django.db.transaction.commit\"><code class=\"xref py py-func docutils literal notranslate\"><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 notranslate\"><span class=\"pre\">rollback()</span></code></a>, before turning autocommit back on.</p>\n<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 notranslate\"><span class=\"pre\">atomic()</span></code></a> block is\nactive, because that would break atomicity.</p>\n</section>\n<section id=\"transactions\">\n<h3>Transactions<a class=\"heading-anchor\" href=\"#transactions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>A transaction is an atomic set of database queries. Even if your program\ncrashes, the database guarantees that either all the changes will be applied,\nor none of them.</p>\n<p>Django doesn't provide an API to start a transaction. The expected way to\nstart 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 notranslate\"><span class=\"pre\">set_autocommit()</span></code></a>.</p>\n<p>Once you're in a transaction, you can choose either to apply the changes\nyou'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 notranslate\"><span class=\"pre\">commit()</span></code></a>, or to cancel them with\n<a class=\"reference internal\" href=\"#django.db.transaction.rollback\" title=\"django.db.transaction.rollback\"><code class=\"xref py py-func docutils literal notranslate\"><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 notranslate\"><span class=\"pre\">django.db.transaction</span></code></a>.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.commit\">\n<span class=\"sig-name descname\"><span class=\"pre\">commit</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.commit\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.rollback\">\n<span class=\"sig-name descname\"><span class=\"pre\">rollback</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.rollback\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>These functions take a <code class=\"docutils literal notranslate\"><span class=\"pre\">using</span></code> argument which should be the name of a\ndatabase. If it isn't provided, Django uses the <code class=\"docutils literal notranslate\"><span class=\"pre\">&quot;default&quot;</span></code> database.</p>\n<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 notranslate\"><span class=\"pre\">atomic()</span></code></a> block is\nactive, because that would break atomicity.</p>\n</section>\n<section id=\"topics-db-transactions-savepoints\">\n<span id=\"id4\"></span><h3>Savepoints<a class=\"heading-anchor\" href=\"#topics-db-transactions-savepoints\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>A savepoint is a marker within a transaction that enables you to roll back\npart of a transaction, rather than the full transaction. Savepoints are\navailable with the SQLite, PostgreSQL, Oracle, and MySQL (when using the InnoDB\nstorage engine) backends. Other backends provide the savepoint functions, but\nthey're empty operations -- they don't actually do anything.</p>\n<p>Savepoints aren't especially useful if you are using autocommit, the default\nbehavior 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 notranslate\"><span class=\"pre\">atomic()</span></code></a>,\nyou build up a series of database operations awaiting a commit or rollback. If\nyou issue a rollback, the entire transaction is rolled back. Savepoints\nprovide the ability to perform a fine-grained rollback, rather than the full\nrollback that would be performed by <code class=\"docutils literal notranslate\"><span class=\"pre\">transaction.rollback()</span></code>.</p>\n<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 notranslate\"><span class=\"pre\">atomic()</span></code></a> decorator is nested, it creates a savepoint to allow\npartial commit or rollback. You'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 notranslate\"><span class=\"pre\">atomic()</span></code></a>\nrather than the functions described below, but they're still part of the\npublic API, and there's no plan to deprecate them.</p>\n<p>Each of these functions takes a <code class=\"docutils literal notranslate\"><span class=\"pre\">using</span></code> argument which should be the name of\na database for which the behavior applies.  If no <code class=\"docutils literal notranslate\"><span class=\"pre\">using</span></code> argument is\nprovided then the <code class=\"docutils literal notranslate\"><span class=\"pre\">&quot;default&quot;</span></code> database is used.</p>\n<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 notranslate\"><span class=\"pre\">django.db.transaction</span></code></a>:</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.savepoint\">\n<span class=\"sig-name descname\"><span class=\"pre\">savepoint</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.savepoint\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Creates a new savepoint. This marks a point in the transaction that is\nknown to be in a &quot;good&quot; state. Returns the savepoint ID (<code class=\"docutils literal notranslate\"><span class=\"pre\">sid</span></code>).</p>\n</dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.savepoint_commit\">\n<span class=\"sig-name descname\"><span class=\"pre\">savepoint_commit</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">sid</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.savepoint_commit\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Releases savepoint <code class=\"docutils literal notranslate\"><span class=\"pre\">sid</span></code>. The changes performed since the savepoint was\ncreated become part of the transaction.</p>\n</dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.savepoint_rollback\">\n<span class=\"sig-name descname\"><span class=\"pre\">savepoint_rollback</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">sid</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.savepoint_rollback\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Rolls back the transaction to savepoint <code class=\"docutils literal notranslate\"><span class=\"pre\">sid</span></code>.</p>\n</dd></dl>\n\n<p>These functions do nothing if savepoints aren't supported or if the database\nis in autocommit mode.</p>\n<p>In addition, there's a utility function:</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.clean_savepoints\">\n<span class=\"sig-name descname\"><span class=\"pre\">clean_savepoints</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.clean_savepoints\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Resets the counter used to generate unique savepoint IDs.</p>\n</dd></dl>\n\n<p>The following example demonstrates the use of savepoints:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">transaction</span>\n\n\n<span class=\"c1\"># open a transaction</span>\n<span class=\"nd\">@transaction</span><span class=\"o\">.</span><span class=\"n\">atomic</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">viewfunc</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">a</span><span class=\"o\">.</span><span class=\"n\">save</span><span class=\"p\">()</span>\n    <span class=\"c1\"># transaction now contains a.save()</span>\n\n    <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>\n\n    <span class=\"n\">b</span><span class=\"o\">.</span><span class=\"n\">save</span><span class=\"p\">()</span>\n    <span class=\"c1\"># transaction now contains a.save() and b.save()</span>\n\n    <span class=\"k\">if</span> <span class=\"n\">want_to_keep_b</span><span class=\"p\">:</span>\n        <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>\n        <span class=\"c1\"># open transaction still contains a.save() and b.save()</span>\n    <span class=\"k\">else</span><span class=\"p\">:</span>\n        <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>\n        <span class=\"c1\"># open transaction now contains only a.save()</span>\n</code></pre></div>\n<p>Savepoints may be used to recover from a database error by performing a partial\nrollback. If you'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 notranslate\"><span class=\"pre\">atomic()</span></code></a> block, the entire block\nwill still be rolled back, because it doesn't know you've handled the situation\nat a lower level! To prevent this, you can control the rollback behavior with\nthe following functions.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.get_rollback\">\n<span class=\"sig-name descname\"><span class=\"pre\">get_rollback</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.get_rollback\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.transaction.set_rollback\">\n<span class=\"sig-name descname\"><span class=\"pre\">set_rollback</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">rollback</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.transaction.set_rollback\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Setting the rollback flag to <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code> forces a rollback when exiting the\ninnermost atomic block. This may be useful to trigger a rollback without\nraising an exception.</p>\n<p>Setting it to <code class=\"docutils literal notranslate\"><span class=\"pre\">False</span></code> prevents such a rollback. Before doing that, make sure\nyou've rolled back the transaction to a known-good savepoint within the current\natomic block! Otherwise you're breaking atomicity and data corruption may\noccur.</p>\n</section>\n</section>\n<section id=\"database-specific-notes\">\n<h2>Database-specific notes<a class=\"heading-anchor\" href=\"#database-specific-notes\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"savepoints-in-sqlite\">\n<span id=\"id5\"></span><h3>Savepoints in SQLite<a class=\"heading-anchor\" href=\"#savepoints-in-sqlite\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>While SQLite supports savepoints, a flaw in the design of the <a class=\"reference external\" href=\"https://docs.python.org/3/library/sqlite3.html#module-sqlite3\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">sqlite3</span></code></a>\nmodule makes them hardly usable.</p>\n<p>When autocommit is enabled, savepoints don't make sense. When it's disabled,\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/sqlite3.html#module-sqlite3\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">sqlite3</span></code></a> commits implicitly before savepoint statements. (In fact, it\ncommits before any statement other than <code class=\"docutils literal notranslate\"><span class=\"pre\">SELECT</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">INSERT</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">UPDATE</span></code>,\n<code class=\"docutils literal notranslate\"><span class=\"pre\">DELETE</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">REPLACE</span></code>.) This bug has two consequences:</p>\n<ul class=\"simple\">\n<li><p>The low level APIs for savepoints are only usable inside a transaction i.e.\ninside an <a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> block.</p></li>\n<li><p>It'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 notranslate\"><span class=\"pre\">atomic()</span></code></a> when autocommit is turned off.</p></li>\n</ul>\n</section>\n<section id=\"transactions-in-mysql\">\n<h3>Transactions in MySQL<a class=\"heading-anchor\" href=\"#transactions-in-mysql\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If you're using MySQL, your tables may or may not support transactions; it\ndepends on your MySQL version and the table types you're using. (By\n&quot;table types,&quot; we mean something like &quot;InnoDB&quot; or &quot;MyISAM&quot;.) MySQL transaction\npeculiarities are outside the scope of this article, but the MySQL site has\n<a class=\"reference external\" href=\"https://dev.mysql.com/doc/refman/en/sql-transactional-statements.html\">information on MySQL transactions</a>.</p>\n<p>If your MySQL setup does <em>not</em> support transactions, then Django will always\nfunction in autocommit mode: statements will be executed and committed as soon\nas they're called. If your MySQL setup <em>does</em> support transactions, Django\nwill handle transactions as explained in this document.</p>\n</section>\n<section id=\"handling-exceptions-within-postgresql-transactions\">\n<h3>Handling exceptions within PostgreSQL transactions<a class=\"heading-anchor\" href=\"#handling-exceptions-within-postgresql-transactions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>This section is relevant only if you're implementing your own transaction\nmanagement. This problem cannot occur in Django's default mode and\n<a class=\"reference internal\" href=\"#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> handles it automatically.</p>\n</aside>\n<p>Inside a transaction, when a call to a PostgreSQL cursor raises an exception\n(typically <code class=\"docutils literal notranslate\"><span class=\"pre\">IntegrityError</span></code>), all subsequent SQL in the same transaction\nwill fail with the error &quot;current transaction is aborted, queries ignored\nuntil end of transaction block&quot;. While the basic use of <code class=\"docutils literal notranslate\"><span class=\"pre\">save()</span></code> is unlikely\nto raise an exception in PostgreSQL, there are more advanced usage patterns\nwhich might, such as saving objects with unique fields, saving using the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">force_insert</span></code>/<code class=\"docutils literal notranslate\"><span class=\"pre\">force_update</span></code> flag, or invoking custom SQL.</p>\n<p>There are several ways to recover from this sort of error.</p>\n<section id=\"transaction-rollback\">\n<h4>Transaction rollback<a class=\"heading-anchor\" href=\"#transaction-rollback\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>The first option is to roll back the entire transaction. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><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>\n<span class=\"k\">try</span><span class=\"p\">:</span>\n    <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>\n<span class=\"k\">except</span> <span class=\"n\">IntegrityError</span><span class=\"p\">:</span>\n    <span class=\"n\">transaction</span><span class=\"o\">.</span><span class=\"n\">rollback</span><span class=\"p\">()</span>\n<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>\n</code></pre></div>\n<p>Calling <code class=\"docutils literal notranslate\"><span class=\"pre\">transaction.rollback()</span></code> rolls back the entire transaction. Any\nuncommitted database operations will be lost. In this example, the changes\nmade by <code class=\"docutils literal notranslate\"><span class=\"pre\">a.save()</span></code> would be lost, even though that operation raised no error\nitself.</p>\n</section>\n<section id=\"savepoint-rollback\">\n<h4>Savepoint rollback<a class=\"heading-anchor\" href=\"#savepoint-rollback\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>You can use <a class=\"reference internal\" href=\"#topics-db-transactions-savepoints\"><span class=\"std std-ref\">savepoints</span></a> to control\nthe extent of a rollback. Before performing a database operation that could\nfail, you can set or update the savepoint; that way, if the operation fails,\nyou can roll back the single offending operation, rather than the entire\ntransaction. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><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>\n<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>\n<span class=\"k\">try</span><span class=\"p\">:</span>\n    <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>\n    <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>\n<span class=\"k\">except</span> <span class=\"n\">IntegrityError</span><span class=\"p\">:</span>\n    <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>\n<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>\n</code></pre></div>\n<p>In this example, <code class=\"docutils literal notranslate\"><span class=\"pre\">a.save()</span></code> will not be undone in the case where\n<code class=\"docutils literal notranslate\"><span class=\"pre\">b.save()</span></code> raises an exception.</p>\n</section>\n</section>\n</section>","rootId":"module-django.db.transaction","toc":[{"title":"データベースのトランザクションを管理する","anchor":"managing-database-transactions","children":[{"title":"Django のデフォルトのトランザクションの動作","anchor":"django-s-default-transaction-behavior","children":[]},{"title":"HTTP リクエストにトランザクションを結びつける","anchor":"tying-transactions-to-http-requests","children":[]},{"title":"明示的にトランザクションをコントロールする","anchor":"controlling-transactions-explicitly","children":[]}]},{"title":"自動コミット","anchor":"autocommit","children":[{"title":"なぜ Django は自動コミットを使うのか","anchor":"why-django-uses-autocommit","children":[]},{"title":"Deactivating transaction management","anchor":"deactivating-transaction-management","children":[]}]},{"title":"Performing actions after commit","anchor":"performing-actions-after-commit","children":[{"title":"Savepoints","anchor":"savepoints","children":[]},{"title":"Order of execution","anchor":"order-of-execution","children":[]},{"title":"Exception handling","anchor":"exception-handling","children":[]},{"title":"Timing of execution","anchor":"timing-of-execution","children":[]},{"title":"Use in tests","anchor":"use-in-tests","children":[]},{"title":"Why no rollback hook?","anchor":"why-no-rollback-hook","children":[]}]},{"title":"Low-level APIs","anchor":"low-level-apis","children":[{"title":"自動コミット","anchor":"managing-autocommit","children":[]},{"title":"Transactions","anchor":"transactions","children":[]},{"title":"Savepoints","anchor":"topics-db-transactions-savepoints","children":[]}]},{"title":"Database-specific notes","anchor":"database-specific-notes","children":[{"title":"Savepoints in SQLite","anchor":"savepoints-in-sqlite","children":[]},{"title":"Transactions in MySQL","anchor":"transactions-in-mysql","children":[]},{"title":"Handling exceptions within PostgreSQL transactions","anchor":"handling-exceptions-within-postgresql-transactions","children":[{"title":"Transaction rollback","anchor":"transaction-rollback","children":[]},{"title":"Savepoint rollback","anchor":"savepoint-rollback","children":[]}]}]}],"breadcrumbs":[{"docname":"topics/index","title":"Django を使う","url":"/ja/4.2/topics/"},{"docname":"topics/db/index","title":"モデルとデータベース","url":"/ja/4.2/topics/db/"}],"prev":{"docname":"topics/db/sql","title":"素の SQL 文の実行","url":"/ja/4.2/topics/db/sql/"},"next":{"docname":"topics/db/multi-db","title":"複数のデータベース","url":"/ja/4.2/topics/db/multi-db/"},"formats":{"html":"/ja/4.2/topics/db/transactions/","markdown":"/ja/4.2/topics/db/transactions.md","json":"/ja/4.2/topics/db/transactions.json"},"source":"https://github.com/django/django/blob/stable/4.2.x/docs/topics/db/transactions.txt","official":"https://docs.djangoproject.com/ja/4.2/topics/db/transactions/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10","1.9"],"inLocales":["en","zh-hans","fr","ja","id","it","pt-br","ko","es","el","pl"]}