{"title":"マイグレーション","version":"3.1","locale":"ja","docname":"topics/migrations","url":"/ja/3.1/topics/migrations/","canonical":"https://djangodocs.dev/ja/3.1/topics/migrations/","summary":"マイグレーション (Migrations) は、Django でモデルに対して行った変更 (フィールドの追加やモデルの削除など) をデータベーススキーマに反映させる方法です。大抵のマイグレーションは自動で行われるものの、いつマイグレーションが作られ、いつ実行され、どんな問題がよく起こるのかは、知っておいた方がいいでしょう。…","html":"<span id=\"migrations\"></span><h1>マイグレーション<a class=\"heading-anchor\" href=\"#module-django.db.migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>マイグレーション (Migrations) は、Django でモデルに対して行った変更 (フィールドの追加やモデルの削除など) をデータベーススキーマに反映させる方法です。大抵のマイグレーションは自動で行われるものの、いつマイグレーションが作られ、いつ実行され、どんな問題がよく起こるのかは、知っておいた方がいいでしょう。</p>\n<section id=\"the-commands\">\n<h2>コマンド<a class=\"heading-anchor\" href=\"#the-commands\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>マイグレーションと Django のデータベーススキーマの操作に関わる時によく使うコマンドを、いくつか挙げておきましょう。</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">migrate</span></code></a> は、マイグレーションを適用したり、適用をキャンセルするのに使います。</p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> は、モデルに対して行った変更をもとに、新しいマイグレーションを作成します。</p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-sqlmigrate\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">sqlmigrate</span></code></a> は、マイグレーションに対応する SQL 文を表示します。</p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-showmigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">showmigrations</span></code></a> は、プロジェクトのマイグレーションとそのステータスをリストします。</p></li>\n</ul>\n<p>マイグレーションというのは、データベーススキーマに対するバージョン管理システムのようなものです。<code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code> はモデルの変更点を1つのマイグレーションファイルにパッケージングし(コミットのようなものです)、<code class=\"docutils literal notranslate\"><span class=\"pre\">migrate</span></code> はその変更点をデータベースに適用する、というわけです。</p>\n<p>各アプリのマイグレーションファイルはそのアプリの &quot;migrations&quot; ディレクトリの中に保管され、コードベースの一部としてコミットされ、配布されるようにデザインされています。いったん開発用マシンでマイグレーションファイルが作成されれば、その後、チームメンバーのマシンやステージング環境のマシン上で同一のマイグレーションが行われ、最終的にプロダクション環境でも同じマイグレーションが行われます。</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>アプリのパッケージの名に migrations が含まれ、上書きされてしまう場合には、設定ファイルの <a class=\"reference internal\" href=\"/ja/3.1/ref/settings/#std-setting-MIGRATION_MODULES\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">MIGRATION_MODULES</span></code></a> を修正してください。</p>\n</aside>\n<p>マイグレーションが同じデータセットに同じ方法で実行され、一貫した結果を生み出すということは、開発環境やステージング環境下で目にする結果が、プロダクション環境下でも全く同じになるということです。</p>\n<p>Django will make migrations for any change to your models or fields - even\noptions that don't affect the database - as the only way it can reconstruct\na field correctly is to have all the changes in the history, and you might\nneed those options in some data migrations later on (for example, if you've\nset custom validators).</p>\n</section>\n<section id=\"backend-support\">\n<h2>対応するバックエンド<a class=\"heading-anchor\" href=\"#backend-support\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>マイグレーションは Django で標準で利用できるすべてのバックエンドに対応しています。サードパーティ製のバックエンドでも、プログラムからのスキーマの変更の操作(<a class=\"reference internal\" href=\"/ja/3.1/ref/schema-editor/\"><span class=\"doc\">SchemaEditor</span></a> クラスで実行される)に対応していれば大丈夫です。</p>\n<p>しかし、スキーマのマイグレーションは、データベースによってが得手・不得手があります。注意点を以下で説明します。</p>\n<section id=\"postgresql\">\n<h3>PostgreSQL<a class=\"heading-anchor\" href=\"#postgresql\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>PostgreSQL is the most capable of all the databases here in terms of schema\nsupport.</p>\n<p>The only caveat is that prior to PostgreSQL 11, adding columns with default\nvalues causes a full rewrite of the table, for a time proportional to its size.\nFor this reason, it's recommended you always create new columns with\n<code class=\"docutils literal notranslate\"><span class=\"pre\">null=True</span></code>, as this way they will be added immediately.</p>\n</section>\n<section id=\"mysql\">\n<h3>MySQL<a class=\"heading-anchor\" href=\"#mysql\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>MySQL はスキーマの変更操作周りのトランザクションをサポートしていません。つまり、マイグレーションの適用が失敗した場合には、手動で変更点を調べあげ、やり直さなければならないということです (過去の時点にロールバックすることは不可能ということです)。</p>\n<p>さらに、MySQL はほとんどすべてのスキーマ操作でテーブル全体を書き直すため、カラムを追加・削除するたびに、一般にテーブルの行数に比例した時間がかかってしまいます。遅いハードでは、この操作に100万行あたり1分以上もかかってしまうため、たった数100万行のテーブルに数カラムを追加するだけで、サイトを10分以上ロックすることになります。</p>\n<p>したがって、MySQL にはカラムやテーブルやインデックスの長さに比較的短い制限があり、インデックスが作られたカラムの結合後のサイズにも制限があります。つまり、他のバックエンドでは可能なインデックスであっても、MySQL では作成に失敗してしまうことがあるということです。</p>\n</section>\n<section id=\"sqlite\">\n<h3>SQLite<a class=\"heading-anchor\" href=\"#sqlite\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>SQLite はビルトインのスキーマ変更操作をほとんどサポートしていません。そのため、Django は以下のようにしてスキーマの変更動作をエミュレートします。</p>\n<ul class=\"simple\">\n<li><p>新しいスキーマで、新しいテーブルを作成する</p></li>\n<li><p>テーブル間でデータをコピーする</p></li>\n<li><p>古いテーブルを削除する</p></li>\n<li><p>新しいテーブルを元のテーブル名に変更する</p></li>\n</ul>\n<p>この方法で大抵はうまくいきますが、遅かったりたまにテーブルが壊れてしまうことがあります。そのため、SQLite をプロダクション環境で使用するのは、このリスクと制限を十分理解している場合以外には、おすすめしません。Django がデフォルトで SQLite を使用しているのは、開発者が SQLite をローカルマシンでかんたんに実行できるようにすることで、本格的なデータベースがなくても Django のプロジェクトが開発できるようにして、複雑さを除くようにデザインされているからです。</p>\n</section>\n</section>\n<section id=\"workflow\">\n<h2>ワークフロー<a class=\"heading-anchor\" href=\"#workflow\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django can create migrations for you. Make changes to your models - say, add a\nfield and remove a model - and then run <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</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>$ python manage.py makemigrations\nMigrations for &#39;books&#39;:\n  books/migrations/0003_auto.py:\n    - Alter field author on book\n</code></pre></div>\n<p>すると、あなたが書いたモデルがスキャンされ、現在のバージョンのマイグレーションファイルに記録されているモデルと比較されます。この時、<code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code> があなたが何を変更したと考えているのかを理解するために、出力をよく読んでください。不完全だったり、意図したよりも複雑な結果が表示されるかもしれません。</p>\n<p>問題なく新しいマイグレーションファイルが生成されたら、期待通りに変更が行われるように、データベースに適用します</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>$ python manage.py migrate\nOperations to perform:\n  Apply all migrations: books\nRunning migrations:\n  Rendering model states... DONE\n  Applying books.0003_auto... OK\n</code></pre></div>\n<p>マイグレーションを適用したら、マイグレーションとモデルの変更をバージョン管理システムに1つのコミットとしてコミットしましょう。こうすることで、他の開発者 (やプロダクションサーバー) がコードをチェックアウトした時に、モデルの変更とマイグレーションの適用を同時に実行することができます。</p>\n<p>マイグレーションに、自動生成された名前ではなく、意味のある名前を与えたければ、<a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#cmdoption-makemigrations-name\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">makemigrations</span> <span class=\"pre\">--name</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>$ python manage.py makemigrations --name changed_my_model your_app_label\n</code></pre></div>\n<section id=\"version-control\">\n<h3>バージョン管理<a class=\"heading-anchor\" href=\"#version-control\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>マイグレーションはバージョン管理システムに保管されるため、あなたがマイグレーションをコミットしたのと同じアプリに、同じタイミングで、他の開発者もマイグレーションをコミットしてしまい、結果として同じ数字のマイグレーションが2つできてしまう、というシチュエーションに遭遇するかもしれません。</p>\n<p>でも、大丈夫。マイグレーションの数字は開発者が参考にするために付けられているだけなのです。Django が気にするのは、マイグレーションの名前が異なっているかどうかだけです。マイグレーションはファイルの中で、自分が依存している他のマイグレーション (同じアプリの過去のマイグレーションを含む) を明記しています。そのため、同じアプリへの2つの順序関係がない新しいマイグレーションが存在していれば、それらをちゃんと検出できます。</p>\n<p>このような状況が起きた場合、Django はいくつかの選択肢を提示します。それを読んで十分安全だと判断できれば、2つのマイグレーションを自動的に2つの連続するマイグレーションに変更してくれます。そうでなければ、マイグレーションファイルを自分で修正する必要があります。でも、難しくないので心配はいりません。詳しくは、下の <a class=\"reference internal\" href=\"#migration-files\"><span class=\"std std-ref\">マイグレーションファイル</span></a> で説明しています。</p>\n</section>\n</section>\n<section id=\"transactions\">\n<h2>Transactions<a class=\"heading-anchor\" href=\"#transactions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>On databases that support DDL transactions (SQLite and PostgreSQL), all\nmigration operations will run inside a single transaction by default. In\ncontrast, if a database doesn't support DDL transactions (e.g. MySQL, Oracle)\nthen all operations will run without a transaction.</p>\n<p>You can prevent a migration from running in a transaction by setting the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> attribute to <code class=\"docutils literal notranslate\"><span class=\"pre\">False</span></code>. 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=\"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\">migrations</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n    <span class=\"n\">atomic</span> <span class=\"o\">=</span> <span class=\"kc\">False</span>\n</code></pre></div>\n<p>It's also possible to execute parts of the migration inside a transaction using\n<a class=\"reference internal\" href=\"/ja/3.1/topics/db/transactions/#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 by passing <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic=True</span></code> to\n<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a>. See\n<a class=\"reference internal\" href=\"/ja/3.1/howto/writing-migrations/#non-atomic-migrations\"><span class=\"std std-ref\">非アトミックのマイグレーション</span></a> for more details.</p>\n</section>\n<section id=\"dependencies\">\n<h2>依存関係<a class=\"heading-anchor\" href=\"#dependencies\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>While migrations are per-app, the tables and relationships implied by\nyour models are too complex to be created for one app at a time. When you make\na migration that requires something else to run - for example, you add a\n<code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code> in your <code class=\"docutils literal notranslate\"><span class=\"pre\">books</span></code> app to your <code class=\"docutils literal notranslate\"><span class=\"pre\">authors</span></code> app - the resulting\nmigration will contain a dependency on a migration in <code class=\"docutils literal notranslate\"><span class=\"pre\">authors</span></code>.</p>\n<p>つまり、マイグレーションを実行すると、最初に <code class=\"docutils literal notranslate\"><span class=\"pre\">authors</span></code> のマイグレーションが実行されて <code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code> リファレンスが参照するテーブルが作成され、その後で <code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code> カラムを作るマイグレーションが実行された後、制約が作られます。もしそうでなかったら、<code class=\"docutils literal notranslate\"><span class=\"pre\">books</span></code> のマイグレーションが存在しないテーブルを参照する <code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code> カラムを作ろうとして、結果、データベースはエラーを出してしまうでしょう。</p>\n<p>This dependency behavior affects most migration operations where you\nrestrict to a single app. Restricting to a single app (either in\n<code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code> or <code class=\"docutils literal notranslate\"><span class=\"pre\">migrate</span></code>) is a best-efforts promise, and not\na guarantee; any other apps that need to be used to get dependencies correct\nwill be.</p>\n<p>Apps without migrations must not have relations (<code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code>,\n<code class=\"docutils literal notranslate\"><span class=\"pre\">ManyToManyField</span></code>, etc.) to apps with migrations. Sometimes it may work, but\nit's not supported.</p>\n</section>\n<section id=\"migration-files\">\n<span id=\"id1\"></span><h2>マイグレーションファイル<a class=\"heading-anchor\" href=\"#migration-files\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Migrations are stored as an on-disk format, referred to here as\n&quot;migration files&quot;. These files are actually normal Python files with an\nagreed-upon object layout, written in a declarative style.</p>\n<p>基本的なマイグレーションファイルは、次のような形式です。</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\">migrations</span><span class=\"p\">,</span> <span class=\"n\">models</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[(</span><span class=\"s1\">&#39;migrations&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;0001_initial&#39;</span><span class=\"p\">)]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">DeleteModel</span><span class=\"p\">(</span><span class=\"s1\">&#39;Tribble&#39;</span><span class=\"p\">),</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">AddField</span><span class=\"p\">(</span><span class=\"s1\">&#39;Author&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;rating&#39;</span><span class=\"p\">,</span> <span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">IntegerField</span><span class=\"p\">(</span><span class=\"n\">default</span><span class=\"o\">=</span><span class=\"mi\">0</span><span class=\"p\">)),</span>\n    <span class=\"p\">]</span>\n</code></pre></div>\n<p>Django が (Python モジュールとして) マイグレーションファイルを読み込んだ時に最初に探すのは、<code class=\"docutils literal notranslate\"><span class=\"pre\">Migration</span></code> という名前の <code class=\"docutils literal notranslate\"><span class=\"pre\">django.db.migrations.Migration</span></code> のサブクラスです。そして、このサブクラスの4つの属性を調べますが、ほとんど場合に使われるのは、次の2つの属性です。</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">dependencies</span></code> は、このマイグレーションが依存する他のマイグレーションのリストです。</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">operations</span></code> は、このマイグレーションが行う操作を定義している <code class=\"docutils literal notranslate\"><span class=\"pre\">Operation</span></code> クラスのリストです。</p></li>\n</ul>\n<p>operations がポイントです。これは、宣言的な命令の集まりで、Django にどんなスキーマの変更が必要かを教えます。Django はそれらをスキャンして、全アプリへのスキーマの変更を完全に表現するデータ構造をメモリ上に作り上げ、これを利用して、Django スキーマを実際に変化させる SQL 文を生成します。</p>\n<p>この時に作られるメモリ上のデータ構造は、新しいモデルと現在のマイグレーションの状態の差分を計算するのにも使われます。Django は、メモリ上のモデルの集まりのすべての変更点を順番にたどってゆき、最後に <code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code> した時のモデルの状態を理解します。そして、そのモデルと <code class=\"docutils literal notranslate\"><span class=\"pre\">models.py</span></code> ファイルにあるモデルとを比較し、行った変更に対して作業を行うのです。</p>\n<p>ごく稀にマイグレーションファイルを手で修正しなければならないことがありますが、必要があればすべて手で書くことも特に難しい作業ではありません。複雑なデータベース操作の中には自動的には検出できないものもあり、その場合にはマイグレーションを手で書くことが必須になることがあります。でも必要な場合には、自分の手で書くのを怖がらないでくださいね。</p>\n<section id=\"custom-fields\">\n<h3>カスタムフィールド<a class=\"heading-anchor\" href=\"#custom-fields\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>すでにマイグレートしたカスタムのフィールドの位置引数の数を変更しようとすると、<code class=\"docutils literal notranslate\"><span class=\"pre\">TypeError</span></code> が発生してしまします。古いマイグレーションは、修正した <code class=\"docutils literal notranslate\"><span class=\"pre\">__init__</span></code> メソッドを古い引数で呼んでしまいます。そこで、新しい引数が必要な場合は、キーワード引数を作り、コンストラクタ内に <code class=\"docutils literal notranslate\"><span class=\"pre\">assert</span> <span class=\"pre\">'argument_name'</span> <span class=\"pre\">in</span> <span class=\"pre\">kwargs</span></code> のような一文を追加してください。</p>\n</section>\n<section id=\"model-managers\">\n<span id=\"using-managers-in-migrations\"></span><h3>モデルマネージャ<a class=\"heading-anchor\" href=\"#model-managers\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>オプションとして、マネージャをマイグレーションにシリアライズして、<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> の中で使えるようにすることができます。それには次のように、マネージャクラスの中で <code class=\"docutils literal notranslate\"><span class=\"pre\">use_in_migrations</span></code> 属性を定義します。</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\">class</span><span class=\"w\"> </span><span class=\"nc\">MyManager</span><span class=\"p\">(</span><span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">Manager</span><span class=\"p\">):</span>\n    <span class=\"n\">use_in_migrations</span> <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyModel</span><span class=\"p\">(</span><span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">Model</span><span class=\"p\">):</span>\n    <span class=\"n\">objects</span> <span class=\"o\">=</span> <span class=\"n\">MyManager</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>もし <a class=\"reference internal\" href=\"/ja/3.1/topics/db/managers/#django.db.models.from_queryset\" title=\"django.db.models.from_queryset\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">from_queryset()</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=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyManager</span><span class=\"p\">(</span><span class=\"n\">MyBaseManager</span><span class=\"o\">.</span><span class=\"n\">from_queryset</span><span class=\"p\">(</span><span class=\"n\">CustomQuerySet</span><span class=\"p\">)):</span>\n    <span class=\"n\">use_in_migrations</span> <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyModel</span><span class=\"p\">(</span><span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">Model</span><span class=\"p\">):</span>\n    <span class=\"n\">objects</span> <span class=\"o\">=</span> <span class=\"n\">MyManager</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>それに伴う影響については、マイグレーションにおける <a class=\"reference internal\" href=\"#historical-models\"><span class=\"std std-ref\">Historical models</span></a> のメモも参考にしてください。</p>\n</section>\n<section id=\"initial-migrations\">\n<h3>最初のマイグレーション<a class=\"heading-anchor\" href=\"#initial-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.db.migrations.Migration.initial\">\n<span class=\"sig-prename descclassname\"><span class=\"pre\">Migration.</span></span><span class=\"sig-name descname\"><span class=\"pre\">initial</span></span><a class=\"heading-anchor\" href=\"#django.db.migrations.Migration.initial\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The &quot;initial migrations&quot; for an app are the migrations that create the first\nversion of that app's tables. Usually an app will have one initial migration,\nbut in some cases of complex model interdependencies it may have two or more.</p>\n<p>Initial migrations are marked with an <code class=\"docutils literal notranslate\"><span class=\"pre\">initial</span> <span class=\"pre\">=</span> <span class=\"pre\">True</span></code> class attribute on the\nmigration class. If an <code class=\"docutils literal notranslate\"><span class=\"pre\">initial</span></code> class attribute isn't found, a migration\nwill be considered &quot;initial&quot; if it is the first migration in the app (i.e. if\nit has no dependencies on any other migration in the same app).</p>\n<p>When the <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#cmdoption-migrate-fake-initial\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">migrate</span> <span class=\"pre\">--fake-initial</span></code></a> option is used, these initial\nmigrations are treated specially. For an initial migration that creates one or\nmore tables (<code class=\"docutils literal notranslate\"><span class=\"pre\">CreateModel</span></code> operation), Django checks that all of those tables\nalready exist in the database and fake-applies the migration if so. Similarly,\nfor an initial migration that adds one or more fields (<code class=\"docutils literal notranslate\"><span class=\"pre\">AddField</span></code> operation),\nDjango checks that all of the respective columns already exist in the database\nand fake-applies the migration if so. Without <code class=\"docutils literal notranslate\"><span class=\"pre\">--fake-initial</span></code>, initial\nmigrations are treated no differently from any other migration.</p>\n</section>\n<section id=\"history-consistency\">\n<span id=\"migration-history-consistency\"></span><h3>History consistency<a class=\"heading-anchor\" href=\"#history-consistency\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>As previously discussed, you may need to linearize migrations manually when two\ndevelopment branches are joined. While editing migration dependencies, you can\ninadvertently create an inconsistent history state where a migration has been\napplied but some of its dependencies haven't. This is a strong indication that\nthe dependencies are incorrect, so Django will refuse to run migrations or make\nnew migrations until it's fixed. When using multiple databases, you can use the\n<a class=\"reference internal\" href=\"/ja/3.1/topics/db/multi-db/#allow_migrate\" title=\"allow_migrate\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">allow_migrate()</span></code></a> method of <a class=\"reference internal\" href=\"/ja/3.1/topics/db/multi-db/#topics-db-multi-db-routing\"><span class=\"std std-ref\">database routers</span></a> to control which databases\n<a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> checks for consistent history.</p>\n</section>\n</section>\n<section id=\"adding-migrations-to-apps\">\n<h2>アプリにマイグレーションを追加する<a class=\"heading-anchor\" href=\"#adding-migrations-to-apps\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>New apps come preconfigured to accept migrations, and so you can add migrations\nby running <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> once you've made some changes.</p>\n<p>If your app already has models and database tables, and doesn't have migrations\nyet (for example, you created it against a previous Django version), you'll\nneed to convert it to use migrations by running:</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>$ python manage.py makemigrations your_app_label\n</code></pre></div>\n<p>This will make a new initial migration for your app. Now, run <code class=\"docutils literal notranslate\"><span class=\"pre\">python</span>\n<span class=\"pre\">manage.py</span> <span class=\"pre\">migrate</span> <span class=\"pre\">--fake-initial</span></code>, and Django will detect that you have an\ninitial migration <em>and</em> that the tables it wants to create already exist, and\nwill mark the migration as already applied. (Without the <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#cmdoption-migrate-fake-initial\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">migrate</span>\n<span class=\"pre\">--fake-initial</span></code></a> flag, the command would error out because the tables it wants\nto create already exist.)</p>\n<p>Note that this only works given two things:</p>\n<ul class=\"simple\">\n<li><p>You have not changed your models since you made their tables. For migrations\nto work, you must make the initial migration <em>first</em> and then make changes,\nas Django compares changes against migration files, not the database.</p></li>\n<li><p>You have not manually edited your database - Django won't be able to detect\nthat your database doesn't match your models, you'll just get errors when\nmigrations try to modify those tables.</p></li>\n</ul>\n</section>\n<section id=\"reversing-migrations\">\n<span id=\"id2\"></span><h2>Reversing migrations<a class=\"heading-anchor\" href=\"#reversing-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Migrations can be reversed with <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">migrate</span></code></a> by passing the number of the\nprevious migration. For example, to reverse migration <code class=\"docutils literal notranslate\"><span class=\"pre\">books.0003</span></code>:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-0-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>migrate<span class=\"w\"> </span>books<span class=\"w\"> </span><span class=\"m\">0002</span>\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto... OK</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-0-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate books 0002\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto... OK</span>\n</code></pre></div></div></div>\n<p>If you want to reverse all migrations applied for an app, use the name\n<code class=\"docutils literal notranslate\"><span class=\"pre\">zero</span></code>:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-1-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>migrate<span class=\"w\"> </span>books<span class=\"w\"> </span>zero\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Unapply all migrations: books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0002_auto... OK</span>\n<span class=\"go\">  Unapplying books.0001_initial... OK</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-1-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate books zero\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Unapply all migrations: books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0002_auto... OK</span>\n<span class=\"go\">  Unapplying books.0001_initial... OK</span>\n</code></pre></div></div></div>\n<p>A migration is irreversible if it contains any irreversible operations.\nAttempting to reverse such migrations will raise <code class=\"docutils literal notranslate\"><span class=\"pre\">IrreversibleError</span></code>:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-2-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>migrate<span class=\"w\"> </span>books<span class=\"w\"> </span><span class=\"m\">0002</span>\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto...Traceback (most recent call last):</span>\n<span class=\"go\">django.db.migrations.exceptions.IrreversibleError: Operation &lt;RunSQL  sql=&#39;DROP TABLE demo_books&#39;&gt; in books.0003_auto is not reversible</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-2-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate books 0002\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto...Traceback (most recent call last):</span>\n<span class=\"gp\">django.db.migrations.exceptions.IrreversibleError: Operation &lt;RunSQL  sql=&#39;DROP TABLE demo_books&#39;&gt;</span> in books.0003_auto is not reversible\n</code></pre></div></div></div>\n</section>\n<section id=\"historical-models\">\n<span id=\"id3\"></span><h2>Historical models<a class=\"heading-anchor\" href=\"#historical-models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>When you run migrations, Django is working from historical versions of your\nmodels stored in the migration files. If you write Python code using the\n<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> operation, or if you have\n<code class=\"docutils literal notranslate\"><span class=\"pre\">allow_migrate</span></code> methods on your database routers, you <strong>need to use</strong> these\nhistorical model versions rather than importing them directly.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>If you import models directly rather than using the historical models,\nyour migrations <em>may work initially</em> but will fail in the future when you\ntry to re-run old migrations (commonly, when you set up a new installation\nand run through all the migrations to set up the database).</p>\n<p>This means that historical model problems may not be immediately obvious.\nIf you run into this kind of failure, it's OK to edit the migration to use\nthe historical models rather than direct imports and commit those changes.</p>\n</aside>\n<p>Because it's impossible to serialize arbitrary Python code, these historical\nmodels will not have any custom methods that you have defined. They will,\nhowever, have the same fields, relationships, managers (limited to those with\n<code class=\"docutils literal notranslate\"><span class=\"pre\">use_in_migrations</span> <span class=\"pre\">=</span> <span class=\"pre\">True</span></code>) and <code class=\"docutils literal notranslate\"><span class=\"pre\">Meta</span></code> options (also versioned, so they may\nbe different from your current ones).</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>This means that you will NOT have custom <code class=\"docutils literal notranslate\"><span class=\"pre\">save()</span></code> methods called on objects\nwhen you access them in migrations, and you will NOT have any custom\nconstructors or instance methods. Plan appropriately!</p>\n</aside>\n<p>References to functions in field options such as <code class=\"docutils literal notranslate\"><span class=\"pre\">upload_to</span></code> and\n<code class=\"docutils literal notranslate\"><span class=\"pre\">limit_choices_to</span></code> and model manager declarations with managers having\n<code class=\"docutils literal notranslate\"><span class=\"pre\">use_in_migrations</span> <span class=\"pre\">=</span> <span class=\"pre\">True</span></code> are serialized in migrations, so the functions and\nclasses will need to be kept around for as long as there is a migration\nreferencing them. Any <a class=\"reference internal\" href=\"/ja/3.1/howto/custom-model-fields/\"><span class=\"doc\">custom model fields</span></a>\nwill also need to be kept, since these are imported directly by migrations.</p>\n<p>In addition, the concrete base classes of the model are stored as pointers, so\nyou must always keep base classes around for as long as there is a migration\nthat contains a reference to them. On the plus side, methods and managers from\nthese base classes inherit normally, so if you absolutely need access to these\nyou can opt to move them into a superclass.</p>\n<p>To remove old references, you can <a class=\"reference internal\" href=\"#migration-squashing\"><span class=\"std std-ref\">squash migrations</span></a>\nor, if there aren't many references, copy them into the migration files.</p>\n</section>\n<section id=\"considerations-when-removing-model-fields\">\n<span id=\"migrations-removing-model-fields\"></span><h2>モデルのフィールドを削除するときに考えるべきこと<a class=\"heading-anchor\" href=\"#considerations-when-removing-model-fields\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Similar to the &quot;references to historical functions&quot; considerations described in\nthe previous section, removing custom model fields from your project or\nthird-party app will cause a problem if they are referenced in old migrations.</p>\n<p>To help with this situation, Django provides some model field attributes to\nassist with model field deprecation using the <a class=\"reference internal\" href=\"/ja/3.1/topics/checks/\"><span class=\"doc\">system checks framework</span></a>.</p>\n<p>Add the <code class=\"docutils literal notranslate\"><span class=\"pre\">system_check_deprecated_details</span></code> attribute to your model field\nsimilar to the following:</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\">class</span><span class=\"w\"> </span><span class=\"nc\">IPAddressField</span><span class=\"p\">(</span><span class=\"n\">Field</span><span class=\"p\">):</span>\n    <span class=\"n\">system_check_deprecated_details</span> <span class=\"o\">=</span> <span class=\"p\">{</span>\n        <span class=\"s1\">&#39;msg&#39;</span><span class=\"p\">:</span> <span class=\"p\">(</span>\n            <span class=\"s1\">&#39;IPAddressField has been deprecated. Support for it (except &#39;</span>\n            <span class=\"s1\">&#39;in historical migrations) will be removed in Django 1.9.&#39;</span>\n        <span class=\"p\">),</span>\n        <span class=\"s1\">&#39;hint&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;Use GenericIPAddressField instead.&#39;</span><span class=\"p\">,</span>  <span class=\"c1\"># optional</span>\n        <span class=\"s1\">&#39;id&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;fields.W900&#39;</span><span class=\"p\">,</span>  <span class=\"c1\"># pick a unique ID for your field.</span>\n    <span class=\"p\">}</span>\n</code></pre></div>\n<p>After a deprecation period of your choosing (two or three feature releases for\nfields in Django itself), change the <code class=\"docutils literal notranslate\"><span class=\"pre\">system_check_deprecated_details</span></code>\nattribute to <code class=\"docutils literal notranslate\"><span class=\"pre\">system_check_removed_details</span></code> and update the dictionary similar\nto:</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\">class</span><span class=\"w\"> </span><span class=\"nc\">IPAddressField</span><span class=\"p\">(</span><span class=\"n\">Field</span><span class=\"p\">):</span>\n    <span class=\"n\">system_check_removed_details</span> <span class=\"o\">=</span> <span class=\"p\">{</span>\n        <span class=\"s1\">&#39;msg&#39;</span><span class=\"p\">:</span> <span class=\"p\">(</span>\n            <span class=\"s1\">&#39;IPAddressField has been removed except for support in &#39;</span>\n            <span class=\"s1\">&#39;historical migrations.&#39;</span>\n        <span class=\"p\">),</span>\n        <span class=\"s1\">&#39;hint&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;Use GenericIPAddressField instead.&#39;</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;id&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;fields.E900&#39;</span><span class=\"p\">,</span>  <span class=\"c1\"># pick a unique ID for your field.</span>\n    <span class=\"p\">}</span>\n</code></pre></div>\n<p>You should keep the field's methods that are required for it to operate in\ndatabase migrations such as <code class=\"docutils literal notranslate\"><span class=\"pre\">__init__()</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code>, and\n<code class=\"docutils literal notranslate\"><span class=\"pre\">get_internal_type()</span></code>. Keep this stub field for as long as any migrations\nwhich reference the field exist. For example, after squashing migrations and\nremoving the old ones, you should be able to remove the field completely.</p>\n</section>\n<section id=\"data-migrations\">\n<span id=\"id4\"></span><h2>データのマイグレーション<a class=\"heading-anchor\" href=\"#data-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>As well as changing the database schema, you can also use migrations to change\nthe data in the database itself, in conjunction with the schema if you want.</p>\n<p>Migrations that alter data are usually called &quot;data migrations&quot;; they're best\nwritten as separate migrations, sitting alongside your schema migrations.</p>\n<p>Django can't automatically generate data migrations for you, as it does with\nschema migrations, but it's not very hard to write them. Migration files in\nDjango are made up of <a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/\"><span class=\"doc\">Operations</span></a>, and\nthe main operation you use for data migrations is\n<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a>.</p>\n<p>To start, make an empty migration file you can work from (Django will put\nthe file in the right place, suggest a name, and add dependencies for you):</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\">python</span> <span class=\"n\">manage</span><span class=\"o\">.</span><span class=\"n\">py</span> <span class=\"n\">makemigrations</span> <span class=\"o\">--</span><span class=\"n\">empty</span> <span class=\"n\">yourappname</span>\n</code></pre></div>\n<p>Then, open up the file; it should look something like this:</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=\"c1\"># Generated by Django A.B on YYYY-MM-DD HH:MM</span>\n<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\">migrations</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"p\">(</span><span class=\"s1\">&#39;yourappname&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;0001_initial&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"p\">]</span>\n</code></pre></div>\n<p>Now, all you need to do is create a new function and have\n<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> use it.\n<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> expects a callable as its argument\nwhich takes two arguments - the first is an <a class=\"reference internal\" href=\"/ja/3.1/ref/applications/\"><span class=\"doc\">app registry</span></a> that has the historical versions of all your models\nloaded into it to match where in your history the migration sits, and the\nsecond is a <a class=\"reference internal\" href=\"/ja/3.1/ref/schema-editor/\"><span class=\"doc\">SchemaEditor</span></a>, which you can use to\nmanually effect database schema changes (but beware, doing this can confuse\nthe migration autodetector!)</p>\n<p>Let's write a migration that populates our new <code class=\"docutils literal notranslate\"><span class=\"pre\">name</span></code> field with the combined\nvalues of <code class=\"docutils literal notranslate\"><span class=\"pre\">first_name</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">last_name</span></code> (we've come to our senses and\nrealized that not everyone has first and last names). All we need to do is use\nthe historical model and iterate over the rows:</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\">migrations</span>\n\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">combine_names</span><span class=\"p\">(</span><span class=\"n\">apps</span><span class=\"p\">,</span> <span class=\"n\">schema_editor</span><span class=\"p\">):</span>\n    <span class=\"c1\"># We can&#39;t import the Person model directly as it may be a newer</span>\n    <span class=\"c1\"># version than this migration expects. We use the historical version.</span>\n    <span class=\"n\">Person</span> <span class=\"o\">=</span> <span class=\"n\">apps</span><span class=\"o\">.</span><span class=\"n\">get_model</span><span class=\"p\">(</span><span class=\"s1\">&#39;yourappname&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Person&#39;</span><span class=\"p\">)</span>\n    <span class=\"k\">for</span> <span class=\"n\">person</span> <span class=\"ow\">in</span> <span class=\"n\">Person</span><span class=\"o\">.</span><span class=\"n\">objects</span><span class=\"o\">.</span><span class=\"n\">all</span><span class=\"p\">():</span>\n        <span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s1\">&#39;</span><span class=\"si\">%s</span><span class=\"s1\"> </span><span class=\"si\">%s</span><span class=\"s1\">&#39;</span> <span class=\"o\">%</span> <span class=\"p\">(</span><span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">first_name</span><span class=\"p\">,</span> <span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">last_name</span><span class=\"p\">)</span>\n        <span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">save</span><span class=\"p\">()</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"p\">(</span><span class=\"s1\">&#39;yourappname&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;0001_initial&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">RunPython</span><span class=\"p\">(</span><span class=\"n\">combine_names</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n</code></pre></div>\n<p>Once that's done, we can run <code class=\"docutils literal notranslate\"><span class=\"pre\">python</span> <span class=\"pre\">manage.py</span> <span class=\"pre\">migrate</span></code> as normal and the\ndata migration will run in place alongside other migrations.</p>\n<p>You can pass a second callable to\n<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> to run whatever logic you\nwant executed when migrating backwards. If this callable is omitted, migrating\nbackwards will raise an exception.</p>\n<section id=\"accessing-models-from-other-apps\">\n<h3>Accessing models from other apps<a class=\"heading-anchor\" href=\"#accessing-models-from-other-apps\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>When writing a <code class=\"docutils literal notranslate\"><span class=\"pre\">RunPython</span></code> function that uses models from apps other than the\none in which the migration is located, the migration's <code class=\"docutils literal notranslate\"><span class=\"pre\">dependencies</span></code>\nattribute should include the latest migration of each app that is involved,\notherwise you may get an error similar to: <code class=\"docutils literal notranslate\"><span class=\"pre\">LookupError:</span> <span class=\"pre\">No</span> <span class=\"pre\">installed</span> <span class=\"pre\">app</span>\n<span class=\"pre\">with</span> <span class=\"pre\">label</span> <span class=\"pre\">'myappname'</span></code> when you try to retrieve the model in the <code class=\"docutils literal notranslate\"><span class=\"pre\">RunPython</span></code>\nfunction using <code class=\"docutils literal notranslate\"><span class=\"pre\">apps.get_model()</span></code>.</p>\n<p>In the following example, we have a migration in <code class=\"docutils literal notranslate\"><span class=\"pre\">app1</span></code> which needs to use\nmodels in <code class=\"docutils literal notranslate\"><span class=\"pre\">app2</span></code>. We aren't concerned with the details of <code class=\"docutils literal notranslate\"><span class=\"pre\">move_m1</span></code> other\nthan the fact it will need to access models from both apps. Therefore we've\nadded a dependency that specifies the last migration of <code class=\"docutils literal notranslate\"><span class=\"pre\">app2</span></code>:</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\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"p\">(</span><span class=\"s1\">&#39;app1&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;0001_initial&#39;</span><span class=\"p\">),</span>\n        <span class=\"c1\"># added dependency to enable using models from app2 in move_m1</span>\n        <span class=\"p\">(</span><span class=\"s1\">&#39;app2&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;0004_foobar&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">RunPython</span><span class=\"p\">(</span><span class=\"n\">move_m1</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n</code></pre></div>\n</section>\n<section id=\"more-advanced-migrations\">\n<h3>More advanced migrations<a class=\"heading-anchor\" href=\"#more-advanced-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If you're interested in the more advanced migration operations, or want\nto be able to write your own, see the <a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/\"><span class=\"doc\">migration operations reference</span></a> and the &quot;how-to&quot; on <a class=\"reference internal\" href=\"/ja/3.1/howto/writing-migrations/\"><span class=\"doc\">writing migrations</span></a>.</p>\n</section>\n</section>\n<section id=\"squashing-migrations\">\n<span id=\"migration-squashing\"></span><h2>Squashing migrations<a class=\"heading-anchor\" href=\"#squashing-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>You are encouraged to make migrations freely and not worry about how many you\nhave; the migration code is optimized to deal with hundreds at a time without\nmuch slowdown. However, eventually you will want to move back from having\nseveral hundred migrations to just a few, and that's where squashing comes in.</p>\n<p>Squashing is the act of reducing an existing set of many migrations down to\none (or sometimes a few) migrations which still represent the same changes.</p>\n<p>Django does this by taking all of your existing migrations, extracting their\n<code class=\"docutils literal notranslate\"><span class=\"pre\">Operation</span></code>s and putting them all in sequence, and then running an optimizer\nover them to try and reduce the length of the list - for example, it knows\nthat <a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.CreateModel\" title=\"django.db.migrations.operations.CreateModel\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">CreateModel</span></code></a> and\n<a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.DeleteModel\" title=\"django.db.migrations.operations.DeleteModel\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">DeleteModel</span></code></a> cancel each other out,\nand it knows that <a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.AddField\" title=\"django.db.migrations.operations.AddField\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">AddField</span></code></a> can be\nrolled into <a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.CreateModel\" title=\"django.db.migrations.operations.CreateModel\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">CreateModel</span></code></a>.</p>\n<p>Once the operation sequence has been reduced as much as possible - the amount\npossible depends on how closely intertwined your models are and if you have\nany <a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunSQL\" title=\"django.db.migrations.operations.RunSQL\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunSQL</span></code></a>\nor <a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> operations (which can't\nbe optimized through unless they are marked as <code class=\"docutils literal notranslate\"><span class=\"pre\">elidable</span></code>) - Django will then\nwrite it back out into a new set of migration files.</p>\n<p>These files are marked to say they replace the previously-squashed migrations,\nso they can coexist with the old migration files, and Django will intelligently\nswitch between them depending where you are in the history. If you're still\npart-way through the set of migrations that you squashed, it will keep using\nthem until it hits the end and then switch to the squashed history, while new\ninstalls will use the new squashed migration and skip all the old ones.</p>\n<p>This enables you to squash and not mess up systems currently in production\nthat aren't fully up-to-date yet. The recommended process is to squash, keeping\nthe old files, commit and release, wait until all systems are upgraded with\nthe new release (or if you're a third-party project, ensure your users upgrade\nreleases in order without skipping any), and then remove the old files, commit\nand do a second release.</p>\n<p>The command that backs all this is <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-squashmigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">squashmigrations</span></code></a> - pass it the\napp label and migration name you want to squash up to, and it'll get to work:</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>$ ./manage.py squashmigrations myapp 0004\nWill squash the following migrations:\n - 0001_initial\n - 0002_some_change\n - 0003_another_change\n - 0004_undo_something\nDo you wish to proceed? [yN] y\nOptimizing...\n  Optimized from 12 operations to 7 operations.\nCreated new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_somthing.py\n  You should commit this migration but leave the old ones in place;\n  the new migration will be used for new installs. Once you are sure\n  all instances of the codebase have applied the migrations you squashed,\n  you can delete them.\n</code></pre></div>\n<p>Use the <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#cmdoption-squashmigrations-squashed-name\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">squashmigrations</span> <span class=\"pre\">--squashed-name</span></code></a> option if you want to set\nthe name of the squashed migration rather than use an autogenerated one.</p>\n<p>Note that model interdependencies in Django can get very complex, and squashing\nmay result in migrations that do not run; either mis-optimized (in which case\nyou can try again with <code class=\"docutils literal notranslate\"><span class=\"pre\">--no-optimize</span></code>, though you should also report an issue),\nor with a <code class=\"docutils literal notranslate\"><span class=\"pre\">CircularDependencyError</span></code>, in which case you can manually resolve it.</p>\n<p>To manually resolve a <code class=\"docutils literal notranslate\"><span class=\"pre\">CircularDependencyError</span></code>, break out one of\nthe ForeignKeys in the circular dependency loop into a separate\nmigration, and move the dependency on the other app with it. If you're unsure,\nsee how <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> deals with the problem when asked to create\nbrand new migrations from your models. In a future release of Django,\n<a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-squashmigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">squashmigrations</span></code></a> will be updated to attempt to resolve these errors\nitself.</p>\n<p>Once you've squashed your migration, you should then commit it alongside the\nmigrations it replaces and distribute this change to all running instances\nof your application, making sure that they run <code class=\"docutils literal notranslate\"><span class=\"pre\">migrate</span></code> to store the change\nin their database.</p>\n<p>You must then transition the squashed migration to a normal migration by:</p>\n<ul class=\"simple\">\n<li><p>Deleting all the migration files it replaces.</p></li>\n<li><p>Updating all migrations that depend on the deleted migrations to depend on\nthe squashed migration instead.</p></li>\n<li><p>Removing the <code class=\"docutils literal notranslate\"><span class=\"pre\">replaces</span></code> attribute in the <code class=\"docutils literal notranslate\"><span class=\"pre\">Migration</span></code> class of the\nsquashed migration (this is how Django tells that it is a squashed migration).</p></li>\n</ul>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>Once you've squashed a migration, you should not then re-squash that squashed\nmigration until you have fully transitioned it to a normal migration.</p>\n</aside>\n</section>\n<section id=\"serializing-values\">\n<span id=\"migration-serializing\"></span><h2>値のシリアル化<a class=\"heading-anchor\" href=\"#serializing-values\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Migrations are Python files containing the old definitions of your models\n- thus, to write them, Django must take the current state of your models and\nserialize them out into a file.</p>\n<p>Django はほとんどのオブジェクトをシリアライズできますが、有効な Python 表現へと単純にはシリアライズできないオブジェクトもあります。しかし、任意の値を Python のコードにデコードするような Python の標準は存在しません(<code class=\"docutils literal notranslate\"><span class=\"pre\">repr()</span></code> は基本的な値にしか機能しませんし、import path は指定できません)。</p>\n<p>Django がシリアル化できるのは、以下のオブジェクトです。</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">int</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">float</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">bool</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">str</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">bytes</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">None</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">NoneType</span></code></p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">list</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">set</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">tuple</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">dict</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">range</span></code>.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.date</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.time</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.datetime</span></code> インスタンス (timezone-aware なものも含む)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">decimal.Decimal</span></code> インスタンス</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">enum.Enum</span></code> インスタンス</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">uuid.UUID</span></code> インスタンス</p></li>\n<li><p><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> and <a class=\"reference external\" href=\"https://docs.python.org/3/library/functools.html#functools.partialmethod\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">functools.partialmethod</span></code></a> instances\nwhich have serializable <code class=\"docutils literal notranslate\"><span class=\"pre\">func</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">args</span></code>, and <code class=\"docutils literal notranslate\"><span class=\"pre\">keywords</span></code> values.</p></li>\n<li><p>シリアル化できる値をラッピングした <code class=\"docutils literal notranslate\"><span class=\"pre\">LazyObject</span></code> インスタンス</p></li>\n<li><p>Enumeration types (e.g. <code class=\"docutils literal notranslate\"><span class=\"pre\">TextChoices</span></code> or <code class=\"docutils literal notranslate\"><span class=\"pre\">IntegerChoices</span></code>) instances.</p></li>\n<li><p>任意の Django フィールド</p></li>\n<li><p>任意の関数またはメソッドへのリファレンス (例: <code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.datetime.today</span></code>) (ただし、モジュールのトップレベルのスコープにいなければならない)</p></li>\n<li><p>クラスの本体から使用されている束縛されていないメソッド</p></li>\n<li><p>任意のクラスへのリファレンス (ただし、モジュールのトップレベルのスコープにいなければならない)</p></li>\n<li><p>カスタムの <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> メソッドを持つすべてのオブジェクト (<a class=\"reference internal\" href=\"#custom-deconstruct-method\"><span class=\"std std-ref\">以下を参照</span></a>)</p></li>\n</ul>\n<p>Django は以下のオブジェクトをシリアル化できません。</p>\n<ul class=\"simple\">\n<li><p>ネストしたクラス</p></li>\n<li><p>任意のクラスのインスタンス (例: <code class=\"docutils literal notranslate\"><span class=\"pre\">MyClass(4.3,</span> <span class=\"pre\">5.7)</span></code>)</p></li>\n<li><p>ラムダ式</p></li>\n</ul>\n<section id=\"custom-serializers\">\n<span id=\"custom-migration-serializers\"></span><h3>Custom serializers<a class=\"heading-anchor\" href=\"#custom-serializers\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>You can serialize other types by writing a custom serializer. For example, if\nDjango didn't serialize <a class=\"reference external\" href=\"https://docs.python.org/3/library/decimal.html#decimal.Decimal\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Decimal</span></code></a> by default, you could do\nthis:</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\">decimal</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">Decimal</span>\n\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db.migrations.serializer</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">BaseSerializer</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db.migrations.writer</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">MigrationWriter</span>\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">DecimalSerializer</span><span class=\"p\">(</span><span class=\"n\">BaseSerializer</span><span class=\"p\">):</span>\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">serialize</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"nb\">repr</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">value</span><span class=\"p\">),</span> <span class=\"p\">{</span><span class=\"s1\">&#39;from decimal import Decimal&#39;</span><span class=\"p\">}</span>\n\n<span class=\"n\">MigrationWriter</span><span class=\"o\">.</span><span class=\"n\">register_serializer</span><span class=\"p\">(</span><span class=\"n\">Decimal</span><span class=\"p\">,</span> <span class=\"n\">DecimalSerializer</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>The first argument of <code class=\"docutils literal notranslate\"><span class=\"pre\">MigrationWriter.register_serializer()</span></code> is a type or\niterable of types that should use the serializer.</p>\n<p>The <code class=\"docutils literal notranslate\"><span class=\"pre\">serialize()</span></code> method of your serializer must return a string of how the\nvalue should appear in migrations and a set of any imports that are needed in\nthe migration.</p>\n</section>\n<section id=\"adding-a-deconstruct-method\">\n<span id=\"custom-deconstruct-method\"></span><h3><code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> メソッドを追加する<a class=\"heading-anchor\" href=\"#adding-a-deconstruct-method\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>自作のカスタムクラスに <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> メソッドを実装することで、インスタンスを Django にシリアル化させることができます。このメソッドは引数を取らず、 <code class=\"docutils literal notranslate\"><span class=\"pre\">(path,</span> <span class=\"pre\">args,</span> <span class=\"pre\">kwargs)</span></code> からなる3タプルを返す必要があります。</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">path</span></code> はクラス名を最後に含むクラスへの Python パスでなければなりません (たとえば、<code class=\"docutils literal notranslate\"><span class=\"pre\">myapp.custom_things.MyClass</span></code>)。自作のクラスがモジュールのトップレベルで使用できない場合は、シリアル化することはできません。</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">args</span></code> はクラスの <code class=\"docutils literal notranslate\"><span class=\"pre\">__init__</span></code> メソッドに渡される位置引数のリストでなければなりません。このリストに含まれる要素は、それ自体でシリアル化可能である必要があります。</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">kwargs</span></code> はクラスの <code class=\"docutils literal notranslate\"><span class=\"pre\">__init__</span></code> メソッドに渡されるキーワード引数の dict でなければなりません。すべての値はそれ自体でシリアル化可能である必要があります。</p></li>\n</ul>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>This return value is different from the <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> method\n<a class=\"reference internal\" href=\"/ja/3.1/howto/custom-model-fields/#custom-field-deconstruct-method\"><span class=\"std std-ref\">for custom fields</span></a> which returns a\ntuple of four items.</p>\n</aside>\n<p>Django will write out the value as an instantiation of your class with the\ngiven arguments, similar to the way it writes out references to Django fields.</p>\n<p><a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> が実行されるたびに新しいマイグレーションが作成されるのを防ぐために、クラスに追加情報を与える <code class=\"docutils literal notranslate\"><span class=\"pre\">__eq__()</span></code> メソッドも追加した方がいいでしょう。この関数は、Django のマイグレーションフレームワークが状態の変更を検出するために呼び出します。</p>\n<p>クラスのコンストラクタのすべての引数がそれ自体でシリアル化可能である場合には、次のように <code class=\"docutils literal notranslate\"><span class=\"pre\">django.utils.deconstruct</span></code> の <code class=\"docutils literal notranslate\"><span class=\"pre\">&#64;deconstructible</span></code> クラスデコレータを使うことで <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> メソッドを追加することができます。</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.utils.deconstruct</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">deconstructible</span>\n\n<span class=\"nd\">@deconstructible</span>\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyCustomClass</span><span class=\"p\">:</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">foo</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">foo</span> <span class=\"o\">=</span> <span class=\"n\">foo</span>\n        <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"fm\">__eq__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">other</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">foo</span> <span class=\"o\">==</span> <span class=\"n\">other</span><span class=\"o\">.</span><span class=\"n\">foo</span>\n</code></pre></div>\n<p>デコレータは、コンストラクタに与えられる引数を独自の方法でキャプチャし保存しておきます。そして、<code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> が呼ばれるタイミングで、保存しておいた引数を返すようにしてくれます。</p>\n</section>\n</section>\n<section id=\"supporting-multiple-django-versions\">\n<h2>Django の複数のバージョンをサポートする<a class=\"heading-anchor\" href=\"#supporting-multiple-django-versions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>もしあなたが、モデルを持つサードパーティのアプリのメンテナならば、Django の複数のバージョンをサポートするマイグレーションを入れておきたいでしょう。その場合、必ず <strong>あなたがサポートしたい Django の下限のバージョンで</strong> <a class=\"reference internal\" href=\"/ja/3.1/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> を実行するようにしてください。</p>\n<p>マイグレーションのシステムは、Django の他のポリシーと同じく、後方互換性を持ちます。そのため、Django X.Y で生成されたマイグレーションファイルは、変更なしに Django X.Y+1 で動作します。しかし、マイグレーションのシステムは前方互換性は保証しません。新しい機能が追加され、新しいバージョンの Django でマイグレーションファイルが生成されれば、そのマイグレーションは古いバージョンでは動きません。</p>\n<aside class=\"admonition admonition-seealso\">\n<p class=\"admonition-title\">参考</p>\n<dl class=\"simple\">\n<dt><a class=\"reference internal\" href=\"/ja/3.1/ref/migration-operations/\"><span class=\"doc\">マイグレーション操作リファレンス</span></a></dt><dd><p>スキーマ操作の API、特別な操作、自作の操作の書き方などについて書いてあります。</p>\n</dd>\n<dt><a class=\"reference internal\" href=\"/ja/3.1/howto/writing-migrations/\"><span class=\"doc\">マイグレーション (Migrations) を書くための ”how-to”</span></a></dt><dd><p>遭遇するかもしれない異なるシチュエーション下での、データベースのマイグレーションの構造化方法と書き方を説明しています。</p>\n</dd>\n</dl>\n</aside>\n</section>","rootId":"module-django.db.migrations","toc":[{"title":"コマンド","anchor":"the-commands","children":[]},{"title":"対応するバックエンド","anchor":"backend-support","children":[{"title":"PostgreSQL","anchor":"postgresql","children":[]},{"title":"MySQL","anchor":"mysql","children":[]},{"title":"SQLite","anchor":"sqlite","children":[]}]},{"title":"ワークフロー","anchor":"workflow","children":[{"title":"バージョン管理","anchor":"version-control","children":[]}]},{"title":"Transactions","anchor":"transactions","children":[]},{"title":"依存関係","anchor":"dependencies","children":[]},{"title":"マイグレーションファイル","anchor":"migration-files","children":[{"title":"カスタムフィールド","anchor":"custom-fields","children":[]},{"title":"モデルマネージャ","anchor":"model-managers","children":[]},{"title":"最初のマイグレーション","anchor":"initial-migrations","children":[]},{"title":"History consistency","anchor":"history-consistency","children":[]}]},{"title":"アプリにマイグレーションを追加する","anchor":"adding-migrations-to-apps","children":[]},{"title":"Reversing migrations","anchor":"reversing-migrations","children":[]},{"title":"Historical models","anchor":"historical-models","children":[]},{"title":"モデルのフィールドを削除するときに考えるべきこと","anchor":"considerations-when-removing-model-fields","children":[]},{"title":"データのマイグレーション","anchor":"data-migrations","children":[{"title":"Accessing models from other apps","anchor":"accessing-models-from-other-apps","children":[]},{"title":"More advanced migrations","anchor":"more-advanced-migrations","children":[]}]},{"title":"Squashing migrations","anchor":"squashing-migrations","children":[]},{"title":"値のシリアル化","anchor":"serializing-values","children":[{"title":"Custom serializers","anchor":"custom-serializers","children":[]},{"title":"deconstruct() メソッドを追加する","anchor":"adding-a-deconstruct-method","children":[]}]},{"title":"Django の複数のバージョンをサポートする","anchor":"supporting-multiple-django-versions","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Django を使う","url":"/ja/3.1/topics/"}],"prev":{"docname":"topics/class-based-views/mixins","title":"クラスベースのビューでミックスインを使用する","url":"/ja/3.1/topics/class-based-views/mixins/"},"next":{"docname":"topics/files","title":"ファイルの管理","url":"/ja/3.1/topics/files/"},"formats":{"html":"/ja/3.1/topics/migrations/","markdown":"/ja/3.1/topics/migrations.md","json":"/ja/3.1/topics/migrations.json"},"source":"https://github.com/django/django/blob/stable/3.1.x/docs/topics/migrations.txt","official":"https://docs.djangoproject.com/ja/3.1/topics/migrations/","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","pt-br","ko","es","el","pl"]}