djangoでモデル変更する時に、DB定義も変更

移転しました。

djangoでモデル変更する時に、DB定義も変更したかったのでいろいろ探してみると以下があるらしい。
 South
 django-evolution
 dmigrations
id:nullpobug に聞いてみたところSouthがよさそうとのことで、South使ってみる

以下でもSouthがよいとかいってるな。
http://stackoverflow.com/questions/853248/how-can-you-migrate-django-models-similar-to-ruby-on-rails-migrations

install

easy_install South

Southのテーブルを作成

models.pyにモデルを書いた後syncdbを行うとmigrateするテーブルも事前に作られてしまいmigrateできなくなる。
このためstartapp前(正確にはmodels.pyにモデルを書く前)にsyncdbを行いsouthのテーブルをDBに作成しておく。
すでにmodels.pyを作成してしまっている場合は、settings.pyに書いたINSTALLED_APPSの自作モデルをコメントアウトしてsyncdbを行う。その後、コメントアウトを戻してinitialを行い、migrateするとうまくいく。

django-admin.py startproject mysite
cd mysite
vi settings.py
-----
southを追加
INSTALLED_APPS = (
    'django.contrib.auth',
        :
    'south',
        :
)
-----
python manage.py syncdb   <- ここでsouthのテーブルを作成
python startapp southtut
polls.models.pyの作成
-----
from django.db import models

class Knight(models.Model):
    name = models.CharField(max_length=100)
    of_the_round_table = models.BooleanField()
-----

migrateを試す

migrateの準備
まず初期ファイルを作成
$ ./manage.py schemamigration southtut --initial
Creating migrations directory at '/home/andrew/Programs/litret/southtut/migrations'...
Creating __init__.py in '/home/andrew/Programs/litret/southtut/migrations'...
 + Added model southtut.Knight
Created 0001_initial.py. You can now apply this migration with: ./manage.py migrate southtut

そしてmigrateファイル実行
$ ./manage.py migrate southtut
実際にモデル変更してみる
モデルの変更
-----
from django.db import models

class Knight(models.Model):
    name = models.CharField(max_length=100)
    of_the_round_table = models.BooleanField()
    dances_whenever_able = models.BooleanField()
-----

migrateファイル作成
$ ./manage.py schemamigration southtut --auto
 + Added field dances_whenever_able on southtut.Knight
Created 0002_auto__add_field_knight_dances_whenever_able.py. You can now apply this migration with: ./manage.py migrate southtut

migrate実行
$ ./manage.py migrate southtut
Running migrations for southtut:
 - Migrating forwards to 0002_auto__add_field_knight_dances_whenever_able.
 > southtut:0002_auto__add_field_knight_dances_whenever_able
 - Loading initial data for southtut.

DBにモデルの変更が反映されていることが確認できた。
@AE35の日本語ドキュメントがとても役にちました。