django 1.7 新特性 --- data migration

官方文档:https://docs.djangoproject.com/en/dev/topics/migrations/

1.7 之前大家可能会用south用于管理数据库的模型的同步。1.7之后django已经集成了这个功能。下面做简单示例:

1). 新建一个项目 test_migrations, 并新建一个app: test_m

2). 修改test_migrations的settings.py,使其INSTALLED_APP包含test_m,请修改test_m的models.py文件,如下:

from django.db import models

class test_m(models.Model):
    name = models.CharFiled(max_length=32)

3). 生成迁移文件并迁移,在test_migrations目录下执行以下指令:

./manage.py makemigrations
./manage.py migrate

以上指令会自动将project下面的所有app自动建议新的迁移版本(0001_initial.py,内容如下)并迁移,这个比south要简洁一些。

# -*-  coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

class Migration(migrations.Migration):
    dependencies=[]
    operations = [
        migrations.CreateModel(
            name= 'test_m',
            fields = [
                ('id',models.AutoField(verbose_name='ID',serialize=False,auto_created=True,primary_key=True)),
                ('name',models.CharField(max_length=32))
            ],
            options={},
            bases=(models.Model,)
        ),
    ]

4). 修改2)中的model,添加字段sex,如下:

from django.db import models

class test_m(models.Model):
    name = models.CharField(max_length=32)
    sex = models.CharField(choices=[('m','male'),('f','female')],max_length=32)

5). 再来一次makemigration/migrate,会生成一个0002_test_m_sex.py文件,并询问设置默认值为多少。迁移完成会有如下提示:

Operations  to perform:
    Apply all migrations:admin,contenttypes,test_m,auth,sessions
Running migrations:
    Applying test_m.0002_test_p_sex... OK

  

备注:还有一个命令,用于查看sql,示例如下:

./manage.py sqlmigrate test_m 0002_test_m_sex
BEGIN;
CREATE TABLE "test_m_test_p__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(32) NOT NULL, "sex" varchar(32) NOT NULL);
INSERT INTO "test_m_test_p__new" ("sex", "id", "name") SELECT 'male', "id", "name" FROM "test_perm_test_p";
DROP TABLE "test_m_test_p";
ALTER TABLE "test_m_test_p__new" RENAME TO "test_m_test_p";
原文地址:https://www.cnblogs.com/Tommy-Yu/p/4042602.html