如何在 Django 应用程序的 CI 中处理迁移

How to handle migrations in CI of a django application

我们有一个持续集成环境 git 用于 django 应用程序。

有时我们需要对我们的模型进行修改并将更改迁移到数据库 (pre/pro)。

在我们的钩子中我们做:

python manage.py migrate

它获取之前在我们本地开发环境中创建的迁移并应用它们。但我注意到有时 migrate 会要求用户交互。即:

makemigrations(本地开发)

(project-name-develop)lostcitizen@project-name:~/dev/project-name/project-name.git$ ./manage.py makemigrations
Did you rename publication.writer to publication.author (a ForeignKey)? [y/N] y
Migrations for 'publications':
  0017_auto_20151117_1050.py:
    - Rename field writer on publication to author

迁移(远程)

(project-name-develop)lostcitizen@project-name:~/dev/project-name/project-name.git$ ./manage.py migrate
Skipping creation of NoticeTypes as notification app not found
Operations to perform:
  Synchronize unmigrated apps: landing, about, publications, [...]
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying publications.0016_auto_20151116_1650... OK
  Applying publications.0017_auto_20151117_1050... OK
The following content types are stale and need to be deleted:

    publications | hashtag

Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.

    Type 'yes' to continue, or 'no' to cancel: yes

我的问题是如何处理这个 "safe" 以进行自动部署?我可以手动完成,但我想从其余的开发人员工作流程中抽象出来。

我认为在 git 挂钩中请求用户交互是不可能的,所以我还是使用了这个:

yes | python manage.py migrate

但我认为使用它并不安全。你怎么看?

此致,

您可以使用 --noinput 选项来禁止任何用户提示:

python manage.py migrate --noinput

这将为每个提示选择最安全的选项。

Django commands 有一个 --noinput 开关来帮助解决这种情况。 Migrate 也支持它(参见 python manage.py migrate --help)