迁移是 Django 将你对模型的修改(例如增加一个字段,删除一个模型)应用至数据库表结构对方式。它们被设计的尽可能自动化,但你仍需要知道何时构建和运行迁移,你还需要了解一些常见问题。
命令
以下是几个常用的与迁移交互的命令,即 Django 处理数据库表结构的方式:
-
migrate
,负责应用和撤销迁移。 -
makemigrations
,基于模型的修改创建迁移。 -
sqlmigrate
,展示迁移使用的 SQL 语句。 -
showmigrations
,列出项目的迁移和迁移的状态。
你应该将迁移看作是数据库表结构的版本控制系统。 makemigrations 负责将模型修改打包进独立的迁移文件中——类似提交修改,而 migrate 负责将其应用至数据库。
每个应用的迁移文件位于该应用的 "migrations" 目录中,他们被设计成应用代码的一部分,与应用代码一起被提交,被发布。你只需在开发机上构建一次,就可以在同事的电脑或测试机上运行同样的迁移而保证结果一致。最后在生产环境运行同样的迁移。
注解
通过修改配置
MIGRATION_MODULES
可以重写包含迁移的应用的包名。
从同样的数据集合运行迁移在开发、测试和生产环境都会生成同样的结果。
Django 会在修改模型或字段时生成迁移——即便修改的是不会影响数据库的配置——因为唯一能确保结果正确性的方法时完整记录修改历史,而且这些东西你以后可能在某些数据迁移中用的到(例如,已设置了自定义验证器的时候)
后端支持
所有 Django 支持的数据库后端都支持迁移,还有些支持表修改(通过 SchemaEditor 类实现)的第三方后端也支持。
然而,有些数据库在表结构变更方面比其它数据库更强;下面介绍一些注意事项。
Workflow
Django can create migrations for you. Make changes to your models - say, add a field and remove a model - and then run makemigrations
:
$ python manage.py makemigrations
Migrations for 'books':
books/migrations/0003_auto.py:
- Alter field author on book
Your models will be scanned and compared to the versions currently contained in your migration files, and then a new set of migrations will be written out. Make sure to read the output to see what makemigrations thinks you have changed - it's not perfect, and for complex changes it might not be detecting what you expect.
Once you have your new migration files, you should apply them to your database to make sure they work as expected:
$ python manage.py migrate
Operations to perform:
Apply all migrations: books
Running migrations:
Rendering model states... DONE
Applying books.0003_auto... OK
Once the migration is applied, commit the migration and the models change to your version control system as a single commit - that way, when other developers (or your production servers) check out the code, they'll get both the changes to your models and the accompanying migration at the same time.
If you want to give the migration(s) a meaningful name instead of a generated one, you can use the makemigrations --name
option:
$ python manage.py makemigrations --name changed_my_model your_app_label
网友评论