South

south 是 for django 的一个 db migration 的工具。能方便的做 schema migration 和 data migration.

下面是 tutorial:

http://south.readthedocs.org/en/latest/tutorial/index.html

south 的主要特性有:

1. 能探测 models.py 的更改自动生成必要的 migration 脚本

2. 是以 app 为处理单元的。比如可以指定某些 app 用 south 而其他的继续用 syncdb.

3. 数据库无关

4. 能检测多人同时对同一个 app 的更改冲突(未试验)

south 创建 migration 分为自动和手动两种方式。

自动的方式:

第一次执行时,需要用:

manage.py schemamigration appname --auto --initial

第一次以后只要传 --auto 就可以了。

这个操作后会生成正确的 migration 脚本。接下来,需要通过下列命令执行之,将变更提交到数据库:

manage.py migrate appname

任何时候变更模型后,重复执行上面两句就可以。

高级使用场景

比如在模型中新增了一个非空的列,而表中已有数据了,则在执行 --auto 命令生成 migration script 的时候,south 没法知道对已有的数据,新增的列应该采用什么默认值,所以就会提示,可以根据需要选择取消操作,或者提供一个一次性执行的默认值。

south 可以探测到模型中对字段 unique 属性的更改,生成必要的脚本。

如果涉及到更改了字段名,则可以用:

manage.py schemamigration appname --auto --upgrade

这个命令会删掉之前未提交的一个模型的更改,而重新生成对应到新字段名的迁移脚本。

如何查看 migration 的列表:

manage.py migrate --list

在显示结果中,如果是已提交的,会显示为 (*), 未提交的显示为 ().

同样的这个命令也可以加一个 appname 参数,仅仅查看某一个 app 下的已提交和未提交的 migration 列表。

引申 - 如何查看未执行的 migrations:

manage.py migrate --list | grep -v "*"

Data Migration

比如,User 模型中一开始定义的字段叫做 password, 是明码保存的;

需要改为 hash 保存,删掉原来的明码的字段。

那么做这个操作需要分为3个大的步骤来做:

1. 添加 password_salt, password_hash 两个字段,并执行 schemamigration 命令生成一个迁移脚本;

2. 用 south 的 datamigration 命令生成一个数据迁移的架子文件

manage.py datamigration appname hash_passwords

这个命令执行后 south 会帮你建好一个叫做 hash_passwords.py 的文件在迁移目录下。

打开文件,修改代码如下:

def forwards(self, orm):
    import random, sha, string
    for user in orm.User.objects.all():
        user.password_salt = "".join([random.choice(string.letters) for i in range(8)])
        user.password_hash = sha.sha(user.password_salt + user.password).hexdigest()
        user.save()

3. 删除 models 中的 password 字段,执行一次 --auto 的 schemamigration.

最后,执行:

manage.py migrate appname

这样就可以一次性提交了前面3个步骤所做的更改。

详细见:

http://south.readthedocs.org/en/latest/tutorial/part3.html#tutorial-part-3

 

posted @ 2013-07-04 23:42  woodfox  阅读(229)  评论(0编辑  收藏  举报