マイグレーション

マイグレーション (Migrations) は、Django でモデルに対して行った変更 (フィールドの追加やモデルの削除など) をデータベーススキーマに反映させる方法です。大抵のマイグレーションは自動で行われるものの、いつマイグレーションが作られ、いつ実行され、どんな問題がよく起こるのかは、知っておいた方がいいでしょう。

コマンド

マイグレーションと Django のデータベーススキーマの操作に関わる時によく使うコマンドを、いくつか挙げておきましょう。

  • migrate は、マイグレーションを適用したり、適用をキャンセルするのに使います。
  • makemigrations は、モデルに対して行った変更をもとに、新しいマイグレーションを作成します。
  • sqlmigrate は、マイグレーションに対応する SQL 文を表示します。
  • showmigrations は、プロジェクトのマイグレーションとそのステータスをリストします。

マイグレーションというのは、データベーススキーマに対するバージョン管理システムのようなものです。makemigrations はモデルの変更点を1つのマイグレーションファイルにパッケージングし(コミットのようなものです)、migrate はその変更点をデータベースに適用する、というわけです。

各アプリのマイグレーションファイルはそのアプリの 「migrations」 ディレクトリの中に保管され、コードベースの一部としてコミットされ、配布されるようにデザインされています。いったん開発用マシンでマイグレーションファイルが作成されれば、その後、チームメンバーのマシンやステージング環境のマシン上で同一のマイグレーションが行われ、最終的にプロダクション環境でも同じマイグレーションが行われます。

注釈

アプリのパッケージの名に migrations が含まれ、上書きされてしまう場合には、設定ファイルの MIGRATION_MODULES を修正してください。

マイグレーションが同じデータセットに同じ方法で実行され、一貫した結果を生み出すということは、開発環境やステージング環境下で目にする結果が、プロダクション環境下でも全く同じになるということです。

Django will make migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations later on (for example, if you’ve set custom validators).

対応するバックエンド

マイグレーションは Django で標準で利用できるすべてのバックエンドに対応しています。サードパーティ製のバックエンドでも、プログラムからのスキーマの変更の操作(SchemaEditor クラスで実行される)に対応していれば大丈夫です。

しかし、スキーマのマイグレーションは、データベースによってが得手・不得手があります。注意点を以下で説明します。

PostgreSQL

PostgreSQL は、ここに挙げたデータベースの中では一番よくスキーマの操作をサポートしています。ただひとつ気を付けるべき点は、デフォルト値でカラムを追加すると、テーブル全体の書き換えが発生してしまうことです。これには、テーブルサイズに比例した時間がかかります。

そのため、新しいカラムを作成するときには、常に null=True オプションを付けることをおすすめします。こうすれば、カラムの追加は一瞬で終わります。

MySQL

MySQL はスキーマの変更操作周りのトランザクションをサポートしていません。つまり、マイグレーションの適用が失敗した場合には、手動で変更点を調べあげ、やり直さなければならないということです (過去の時点にロールバックすることは不可能ということです)。

さらに、MySQL はほとんどすべてのスキーマ操作でテーブル全体を書き直すため、カラムを追加・削除するたびに、一般にテーブルの行数に比例した時間がかかってしまいます。遅いハードでは、この操作に100万行あたり1分以上もかかってしまうため、たった数100万行のテーブルに数カラムを追加するだけで、サイトを10分以上ロックすることになります。

したがって、MySQL にはカラムやテーブルやインデックスの長さに比較的短い制限があり、インデックスが作られたカラムの結合後のサイズにも制限があります。つまり、他のバックエンドでは可能なインデックスであっても、MySQL では作成に失敗してしまうことがあるということです。

SQLite

SQLite はビルトインのスキーマ変更操作をほとんどサポートしていません。そのため、Django は以下のようにしてスキーマの変更動作をエミュレートします。

  • 新しいスキーマで、新しいテーブルを作成する
  • テーブル間でデータをコピーする
  • 古いテーブルを削除する
  • 新しいテーブルを元のテーブル名に変更する

この方法で大抵はうまくいきますが、遅かったりたまにテーブルが壊れてしまうことがあります。そのため、SQLite をプロダクション環境で使用するのは、このリスクと制限を十分理解している場合以外には、おすすめしません。Django がデフォルトで SQLite を使用しているのは、開発者が SQLite をローカルマシンでかんたんに実行できるようにすることで、本格的なデータベースがなくても Django のプロジェクトが開発できるようにして、複雑さを除くようにデザインされているからです。

ワークフロー

マイグレーションのワークフローはシンプルです。まず、モデルのフィールドの追加や削除などの変更を行い、そして makemigrations を実行します。

$ python manage.py makemigrations
Migrations for 'books':
  books/migrations/0003_auto.py:
    - Alter field author on book

すると、あなたが書いたモデルがスキャンされ、現在のバージョンのマイグレーションファイルに記録されているモデルと比較されます。この時、makemigrations があなたが何を変更したと考えているのかを理解するために、出力をよく読んでください。不完全だったり、意図したよりも複雑な結果が表示されるかもしれません。

問題なく新しいマイグレーションファイルが生成されたら、期待通りに変更が行われるように、データベースに適用します

$ python manage.py migrate
Operations to perform:
  Apply all migrations: books
Running migrations:
  Rendering model states... DONE
  Applying books.0003_auto... OK

マイグレーションを適用したら、マイグレーションとモデルの変更をバージョン管理システムに1つのコミットとしてコミットしましょう。こうすることで、他の開発者 (やプロダクションサーバー) がコードをチェックアウトした時に、モデルの変更とマイグレーションの適用を同時に実行することができます。

マイグレーションに、自動生成された名前ではなく、意味のある名前を与えたければ、makemigrations --name オプションが使えます。

$ python manage.py makemigrations --name changed_my_model your_app_label

バージョン管理

マイグレーションはバージョン管理システムに保管されるため、あなたがマイグレーションをコミットしたのと同じアプリに、同じタイミングで、他の開発者もマイグレーションをコミットしてしまい、結果として同じ数字のマイグレーションが2つできてしまう、というシチュエーションに遭遇するかもしれません。

でも、大丈夫。マイグレーションの数字は開発者が参考にするために付けられているだけなのです。Django が気にするのは、マイグレーションの名前が異なっているかどうかだけです。マイグレーションはファイルの中で、自分が依存している他のマイグレーション (同じアプリの過去のマイグレーションを含む) を明記しています。そのため、同じアプリへの2つの順序関係がない新しいマイグレーションが存在していれば、それらをちゃんと検出できます。

このような状況が起きた場合、Django はいくつかの選択肢を提示します。それを読んで十分安全だと判断できれば、2つのマイグレーションを自動的に2つの連続するマイグレーションに変更してくれます。そうでなければ、マイグレーションファイルを自分で修正する必要があります。でも、難しくないので心配はいりません。詳しくは、下の :ref:`migration-files で説明しています。

依存関係

マイグレーションはアプリごとに作られますが、モデルが表しているテーブルとリレーションは、一度に一つのアプリに対して作るには複雑すぎます。他のマイグレーションの実行を要求するマイグレーション、たとえば books アプリ内の ForeignKeyauthors アプリに加えるような場合、結果として作られるマイグレーションには、authors のマイグレーションへの依存関係が生じます。

つまり、マイグレーションを実行すると、最初に authors のマイグレーションが実行されて ForeignKey リファレンスが参照するテーブルが作成され、その後で ForeignKey カラムを作るマイグレーションが実行された後、制約が作られます。もしそうでなかったら、books のマイグレーションが存在しないテーブルを参照する ForeignKey カラムを作ろうとして、結果、データベースはエラーを出してしまうでしょう。

This dependency behavior affects most migration operations where you restrict to a single app. Restricting to a single app (either in makemigrations or migrate) is a best-efforts promise, and not a guarantee; any other apps that need to be used to get dependencies correct will be.

マイグレーションファイル

マイグレーションはディスク上のファイルとして保存されます。ここではそれを ”migration files” と呼びます。このファイルは実際には、決まった仕方でオブジェクトを配置した、宣言型のスタイルで書かれたふつうの Python ファイルにすぎません。

基本的なマイグレーションファイルは、次のような形式です。

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [('migrations', '0001_initial')]

    operations = [
        migrations.DeleteModel('Tribble'),
        migrations.AddField('Author', 'rating', models.IntegerField(default=0)),
    ]

Django が (Python モジュールとして) マイグレーションファイルを読み込んだ時に最初に探すのは、Migration という名前の django.db.migrations.Migration のサブクラスです。そして、このサブクラスの4つの属性を調べますが、ほとんど場合に使われるのは、次の2つの属性です。

  • dependencies は、このマイグレーションが依存する他のマイグレーションのリストです。
  • operations は、このマイグレーションが行う操作を定義している Operation クラスのリストです。

operations がポイントです。これは、宣言的な命令の集まりで、Django にどんなスキーマの変更が必要かを教えます。Django はそれらをスキャンして、全アプリへのスキーマの変更を完全に表現するデータ構造をメモリ上に作り上げ、これを利用して、Django スキーマを実際に変化させる SQL 文を生成します。

この時に作られるメモリ上のデータ構造は、新しいモデルと現在のマイグレーションの状態の差分を計算するのにも使われます。Django は、メモリ上のモデルの集まりのすべての変更点を順番にたどってゆき、最後に makemigrations した時のモデルの状態を理解します。そして、そのモデルと models.py ファイルにあるモデルとを比較し、行った変更に対して作業を行うのです。

ごく稀にマイグレーションファイルを手で修正しなければならないことがありますが、必要があればすべて手で書くことも特に難しい作業ではありません。複雑なデータベース操作の中には自動的には検出できないものもあり、その場合にはマイグレーションを手で書くことが必須になることがあります。でも必要な場合には、自分の手で書くのを怖がらないでくださいね。

カスタムフィールド

すでにマイグレートしたカスタムのフィールドの位置引数の数を変更しようとすると、TypeError が発生してしまします。古いマイグレーションは、修正した __init__ メソッドを古い引数で呼んでしまいます。そこで、新しい引数が必要な場合は、キーワード引数を作り、コンストラクタ内に assert 'argument_name' in kwargs のような一文を追加してください。

モデルマネージャ

オプションとして、マネージャをマイグレーションにシリアライズして、RunPython の中で使えるようにすることができます。それには次のように、マネージャクラスの中で use_in_migrations 属性を定義します。

class MyManager(models.Manager):
    use_in_migrations = True

class MyModel(models.Model):
    objects = MyManager()

もし from_queryset() 関数で動的に生成されたマネージャクラスを使うなら、インポートできるように生成されたクラスを継承する必要があります。

class MyManager(MyBaseManager.from_queryset(CustomQuerySet)):
    use_in_migrations = True

class MyModel(models.Model):
    objects = MyManager()

それに伴う影響については、マイグレーションにおける Historical models のメモも参考にしてください。

最初のマイグレーション

Migration.initial

The 「initial migrations」 for an app are the migrations that create the first version of that app’s tables. Usually an app will have just one initial migration, but in some cases of complex model interdependencies it may have two or more.

Initial migrations are marked with an initial = True class attribute on the migration class. If an initial class attribute isn’t found, a migration will be considered 「initial」 if it is the first migration in the app (i.e. if it has no dependencies on any other migration in the same app).

When the migrate --fake-initial option is used, these initial migrations are treated specially. For an initial migration that creates one or more tables (CreateModel operation), Django checks that all of those tables already exist in the database and fake-applies the migration if so. Similarly, for an initial migration that adds one or more fields (AddField operation), Django checks that all of the respective columns already exist in the database and fake-applies the migration if so. Without --fake-initial, initial migrations are treated no differently from any other migration.

History consistency

As previously discussed, you may need to linearize migrations manually when two development branches are joined. While editing migration dependencies, you can inadvertently create an inconsistent history state where a migration has been applied but some of its dependencies haven’t. This is a strong indication that the dependencies are incorrect, so Django will refuse to run migrations or make new migrations until it’s fixed. When using multiple databases, you can use the allow_migrate() method of database routers to control which databases makemigrations checks for consistent history.

Changed in Django 1.10:

Migration consistency checks were added. Checks based on database routers were added in 1.10.1.

アプリにマイグレーションを追加する

Adding migrations to new apps is straightforward - they come preconfigured to accept migrations, and so just run makemigrations once you’ve made some changes.

If your app already has models and database tables, and doesn’t have migrations yet (for example, you created it against a previous Django version), you’ll need to convert it to use migrations; this is a simple process:

$ python manage.py makemigrations your_app_label

This will make a new initial migration for your app. Now, run python manage.py migrate --fake-initial, and Django will detect that you have an initial migration and that the tables it wants to create already exist, and will mark the migration as already applied. (Without the migrate --fake-initial flag, the command would error out because the tables it wants to create already exist.)

Note that this only works given two things:

  • You have not changed your models since you made their tables. For migrations to work, you must make the initial migration first and then make changes, as Django compares changes against migration files, not the database.
  • You have not manually edited your database - Django won’t be able to detect that your database doesn’t match your models, you’ll just get errors when migrations try to modify those tables.

Historical models

When you run migrations, Django is working from historical versions of your models stored in the migration files. If you write Python code using the RunPython operation, or if you have allow_migrate methods on your database routers, you will be exposed to these versions of your models.

Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True) and Meta options (also versioned, so they may be different from your current ones).

警告

This means that you will NOT have custom save() methods called on objects when you access them in migrations, and you will NOT have any custom constructors or instance methods. Plan appropriately!

References to functions in field options such as upload_to and limit_choices_to and model manager declarations with managers having use_in_migrations = True are serialized in migrations, so the functions and classes will need to be kept around for as long as there is a migration referencing them. Any custom model fields will also need to be kept, since these are imported directly by migrations.

In addition, the base classes of the model are just stored as pointers, so you must always keep base classes around for as long as there is a migration that contains a reference to them. On the plus side, methods and managers from these base classes inherit normally, so if you absolutely need access to these you can opt to move them into a superclass.

To remove old references, you can squash migrations or, if there aren’t many references, copy them into the migration files.

モデルのフィールドを削除するときに考えるべきこと

Similar to the 「references to historical functions」 considerations described in the previous section, removing custom model fields from your project or third-party app will cause a problem if they are referenced in old migrations.

To help with this situation, Django provides some model field attributes to assist with model field deprecation using the system checks framework.

Add the system_check_deprecated_details attribute to your model field similar to the following:

class IPAddressField(Field):
    system_check_deprecated_details = {
        'msg': (
            'IPAddressField has been deprecated. Support for it (except '
            'in historical migrations) will be removed in Django 1.9.'
        ),
        'hint': 'Use GenericIPAddressField instead.',  # optional
        'id': 'fields.W900',  # pick a unique ID for your field.
    }

After a deprecation period of your choosing (two or three feature releases for fields in Django itself), change the system_check_deprecated_details attribute to system_check_removed_details and update the dictionary similar to:

class IPAddressField(Field):
    system_check_removed_details = {
        'msg': (
            'IPAddressField has been removed except for support in '
            'historical migrations.'
        ),
        'hint': 'Use GenericIPAddressField instead.',
        'id': 'fields.E900',  # pick a unique ID for your field.
    }

You should keep the field’s methods that are required for it to operate in database migrations such as __init__(), deconstruct(), and get_internal_type(). Keep this stub field for as long as any migrations which reference the field exist. For example, after squashing migrations and removing the old ones, you should be able to remove the field completely.

データのマイグレーション

As well as changing the database schema, you can also use migrations to change the data in the database itself, in conjunction with the schema if you want.

Migrations that alter data are usually called 「data migrations」; they’re best written as separate migrations, sitting alongside your schema migrations.

Django can’t automatically generate data migrations for you, as it does with schema migrations, but it’s not very hard to write them. Migration files in Django are made up of Operations, and the main operation you use for data migrations is RunPython.

To start, make an empty migration file you can work from (Django will put the file in the right place, suggest a name, and add dependencies for you):

python manage.py makemigrations --empty yourappname

Then, open up the file; it should look something like this:

# -*- coding: utf-8 -*-
# Generated by Django A.B on YYYY-MM-DD HH:MM
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
    ]

Now, all you need to do is create a new function and have RunPython use it. RunPython expects a callable as its argument which takes two arguments - the first is an app registry that has the historical versions of all your models loaded into it to match where in your history the migration sits, and the second is a SchemaEditor, which you can use to manually effect database schema changes (but beware, doing this can confuse the migration autodetector!)

Let’s write a simple migration that populates our new name field with the combined values of first_name and last_name (we’ve come to our senses and realized that not everyone has first and last names). All we need to do is use the historical model and iterate over the rows:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations

def combine_names(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model('yourappname', 'Person')
    for person in Person.objects.all():
        person.name = '%s %s' % (person.first_name, person.last_name)
        person.save()

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(combine_names),
    ]

Once that’s done, we can just run python manage.py migrate as normal and the data migration will run in place alongside other migrations.

You can pass a second callable to RunPython to run whatever logic you want executed when migrating backwards. If this callable is omitted, migrating backwards will raise an exception.

Accessing models from other apps

When writing a RunPython function that uses models from apps other than the one in which the migration is located, the migration’s dependencies attribute should include the latest migration of each app that is involved, otherwise you may get an error similar to: LookupError: No installed app with label 'myappname' when you try to retrieve the model in the RunPython function using apps.get_model().

In the following example, we have a migration in app1 which needs to use models in app2. We aren’t concerned with the details of move_m1 other than the fact it will need to access models from both apps. Therefore we’ve added a dependency that specifies the last migration of app2:

class Migration(migrations.Migration):

    dependencies = [
        ('app1', '0001_initial'),
        # added dependency to enable using models from app2 in move_m1
        ('app2', '0004_foobar'),
    ]

    operations = [
        migrations.RunPython(move_m1),
    ]

More advanced migrations

If you’re interested in the more advanced migration operations, or want to be able to write your own, see the migration operations reference and the 「how-to」 on writing migrations.

Squashing migrations

You are encouraged to make migrations freely and not worry about how many you have; the migration code is optimized to deal with hundreds at a time without much slowdown. However, eventually you will want to move back from having several hundred migrations to just a few, and that’s where squashing comes in.

Squashing is the act of reducing an existing set of many migrations down to one (or sometimes a few) migrations which still represent the same changes.

Django does this by taking all of your existing migrations, extracting their Operations and putting them all in sequence, and then running an optimizer over them to try and reduce the length of the list - for example, it knows that CreateModel and DeleteModel cancel each other out, and it knows that AddField can be rolled into CreateModel.

Once the operation sequence has been reduced as much as possible - the amount possible depends on how closely intertwined your models are and if you have any RunSQL or RunPython operations (which can’t be optimized through unless they are marked as elidable) - Django will then write it back out into a new set of migration files.

These files are marked to say they replace the previously-squashed migrations, so they can coexist with the old migration files, and Django will intelligently switch between them depending where you are in the history. If you’re still part-way through the set of migrations that you squashed, it will keep using them until it hits the end and then switch to the squashed history, while new installs will just use the new squashed migration and skip all the old ones.

This enables you to squash and not mess up systems currently in production that aren’t fully up-to-date yet. The recommended process is to squash, keeping the old files, commit and release, wait until all systems are upgraded with the new release (or if you’re a third-party project, just ensure your users upgrade releases in order without skipping any), and then remove the old files, commit and do a second release.

The command that backs all this is squashmigrations - just pass it the app label and migration name you want to squash up to, and it’ll get to work:

$ ./manage.py squashmigrations myapp 0004
Will squash the following migrations:
 - 0001_initial
 - 0002_some_change
 - 0003_another_change
 - 0004_undo_something
Do you wish to proceed? [yN] y
Optimizing...
  Optimized from 12 operations to 7 operations.
Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_somthing.py
  You should commit this migration but leave the old ones in place;
  the new migration will be used for new installs. Once you are sure
  all instances of the codebase have applied the migrations you squashed,
  you can delete them.

Note that model interdependencies in Django can get very complex, and squashing may result in migrations that do not run; either mis-optimized (in which case you can try again with --no-optimize, though you should also report an issue), or with a CircularDependencyError, in which case you can manually resolve it.

To manually resolve a CircularDependencyError, break out one of the ForeignKeys in the circular dependency loop into a separate migration, and move the dependency on the other app with it. If you’re unsure, see how makemigrations deals with the problem when asked to create brand new migrations from your models. In a future release of Django, squashmigrations will be updated to attempt to resolve these errors itself.

Once you’ve squashed your migration, you should then commit it alongside the migrations it replaces and distribute this change to all running instances of your application, making sure that they run migrate to store the change in their database.

You must then transition the squashed migration to a normal migration by:

  • Deleting all the migration files it replaces.
  • Updating all migrations that depend on the deleted migrations to depend on the squashed migration instead.
  • Removing the replaces attribute in the Migration class of the squashed migration (this is how Django tells that it is a squashed migration).

注釈

Once you’ve squashed a migration, you should not then re-squash that squashed migration until you have fully transitioned it to a normal migration.

値のシリアル化

マイグレーションは、モデルの古い定義が書かれた単なる Python ファイルです。よって、マイグレーションを書くには、Django はモデルの現在の状態を取得して、その状態をシリアライズしてファイルに出力できなければなりません。

Django はほとんどのオブジェクトをシリアライズできますが、有効な Python 表現へと単純にはシリアライズできないオブジェクトもあります。しかし、任意の値を Python のコードにデコードするような Python の標準は存在しません(repr() は基本的な値にしか機能しませんし、import path は指定できません)。

Django がシリアル化できるのは、以下のオブジェクトです。

  • int, long, float, bool, str, unicode, bytes, None
  • list, set, tuple, dict
  • datetime.date, datetime.time, datetime.datetime インスタンス (timezone-aware なものも含む)
  • decimal.Decimal インスタンス
  • enum.Enum インスタンス
  • uuid.UUID instances
  • シリアル化できる func, args, keywords の値を持つ functools.partial インスタンス
  • シリアル化できる値をラッピングした LazyObject インスタンス
  • 任意の Django フィールド
  • 任意の関数またはメソッドへのリファレンス (例: datetime.datetime.today) (ただし、モジュールのトップレベルのスコープにいなければならない)
  • 任意のクラスへのリファレンス (ただし、モジュールのトップレベルのスコープにいなければならない)
  • カスタムの deconstruct() メソッドを持つすべてのオブジェクト (以下を参照)
Changed in Django 1.10:

enum.Enum のシリアル化のサポートが追加された。

Changed in Django 1.11:

Serialization support for uuid.UUID was added.

Python3 では、Django は次のオブジェクトをシリアル化できます。

  • クラス本体で使われている束縛されていないメソッド (以下を参照)

Django は以下のオブジェクトをシリアル化できません。

  • ネストしたクラス
  • Arbitrary class instances (e.g. MyClass(4.3, 5.7))
  • ラムダ式

__qualname__ が導入されたのは Python 3 なので、Django が次のパターン (クラス本体で使われている束縛されていないメソッド) をシリアル化できるのは Python 3 のみで、Python 2 ではこのリファレンスのシリアル化は失敗します。

class MyModel(models.Model):

    def upload_to(self):
        return "something dynamic"

    my_file = models.FileField(upload_to=upload_to)

Python 2 を使っているなら、upload_to や同様の呼び出し可能な種類のオブジェクト (例: default) を、クラス本体ではなくメインモジュールの本体に置くことをおすすめします。

deconstruct() メソッドを追加する

You can let Django serialize your own custom class instances by giving the class a deconstruct() method. It takes no arguments, and should return a tuple of three things (path, args, kwargs):

  • path should be the Python path to the class, with the class name included as the last part (for example, myapp.custom_things.MyClass). If your class is not available at the top level of a module it is not serializable.
  • args should be a list of positional arguments to pass to your class』 __init__ method. Everything in this list should itself be serializable.
  • kwargs should be a dict of keyword arguments to pass to your class』 __init__ method. Every value should itself be serializable.

注釈

This return value is different from the deconstruct() method for custom fields which returns a tuple of four items.

Django will write out the value as an instantiation of your class with the given arguments, similar to the way it writes out references to Django fields.

To prevent a new migration from being created each time makemigrations is run, you should also add a __eq__() method to the decorated class. This function will be called by Django’s migration framework to detect changes between states.

As long as all of the arguments to your class』 constructor are themselves serializable, you can use the @deconstructible class decorator from django.utils.deconstruct to add the deconstruct() method:

from django.utils.deconstruct import deconstructible

@deconstructible
class MyCustomClass(object):

    def __init__(self, foo=1):
        self.foo = foo
        ...

    def __eq__(self, other):
        return self.foo == other.foo

The decorator adds logic to capture and preserve the arguments on their way into your constructor, and then returns those arguments exactly when deconstruct() is called.

Python 2 および 3 をサポートする

In order to generate migrations that support both Python 2 and 3, all string literals used in your models and fields (e.g. verbose_name, related_name, etc.), must be consistently either bytestrings or text (unicode) strings in both Python 2 and 3 (rather than bytes in Python 2 and text in Python 3, the default situation for unmarked string literals.) Otherwise running makemigrations under Python 3 will generate spurious new migrations to convert all these string attributes to text.

The easiest way to achieve this is to follow the advice in Django’s Python 3 porting guide and make sure that all your modules begin with from __future__ import unicode_literals, so that all unmarked string literals are always unicode, regardless of Python version. When you add this to an app with existing migrations generated on Python 2, your next run of makemigrations on Python 3 will likely generate many changes as it converts all the bytestring attributes to text strings; this is normal and should only happen once.

Django の複数のバージョンをサポートする

もしあなたが、モデルを持つサードパーティのアプリのメンテナならば、Django の複数のバージョンをサポートするマイグレーションを入れておきたいでしょう。その場合、必ず あなたがサポートしたい Django の下限のバージョンで makemigrations を実行するようにしてください。

マイグレーションのシステムは、Django の他のポリシーと同じく、後方互換性を持ちます。そのため、Django X.Y で生成されたマイグレーションファイルは、変更なしに Django X.Y+1 で動作します。しかし、マイグレーションのシステムは前方互換性は保証しません。新しい機能が追加され、新しいバージョンの Django でマイグレーションファイルが生成されれば、そのマイグレーションは古いバージョンでは動きません。

参考

マイグレーション操作リファレンス
スキーマ操作の API、特別な操作、自作の操作の書き方などについて書いてあります。
マイグレーション (Migrations) を書くための ”how-to”
遭遇するかもしれない異なるシチュエーション下での、データベースのマイグレーションの構造化方法と書き方を説明しています。