--fake-initial 与 --django 迁移中的 --fake?

--fake-initial vs --fake in Django migration?

Django 迁移中 --fake-initial--fake 有什么区别?使用假迁移有什么危险?有人知道吗?非常感谢大家。

我正在使用 django 1.10

the documentation这个很清楚

--假首字母

Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names

你问的是风险,这里是

only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.

--假的

Tells Django to mark the migrations as having been applied or unapplied, but without actually running the SQL to change your database schema.

This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes;

风险再次凸显

be warned that using --fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly.

这个答案不仅适用于 django 1.8+ 版本,也适用于其他版本。

edit 2018 年 11 月:我有时会在这里和其他地方看到建议您删除数据库的答案。这几乎从来都不是正确的做法。如果您删除数据库,您将丢失所有数据。

@e4c5 已经回答了这个问题,但是我想补充一点什么时候使用--fake--fake-initial

假设您有一个来自生产环境的数据库,您希望将其用于开发并在不破坏数据的情况下应用迁移。那样的话 --fake-initial 就派上用场了。

--fake-initial 将强制 Django 查看您的迁移文件并基本上跳过数据库中已有表的创建。但请注意,任何不创建表(而是修改现有表)的迁移都将是 运行.

相反,如果您有一个包含迁移文件的现有项目并且您想要重置现有迁移的历史记录,那么通常使用 --fake

简答

  • --fake 应用迁移
  • --fake-initial 可能会也可能不会应用迁移

更长的答案:

--fake:Django 保留了一个名为 django_migrations 的 table 来了解它在过去应用了哪些迁移,以防止您不小心再次应用它们。 --fake 所做的只是将迁移文件名插入 table、 而实际上 运行 迁移。如果您先手动更改数据库模式,然后再更改模型,并且想绕过 django 的操作,这将很有用。但是,在该步骤中,您是独立的,因此请注意不要以不一致的状态结束。

--fake-initial: 取决于数据库的状态

  • 所有 tables 已经存在于数据库中:在这种情况下,它的工作方式类似于 --fake只检查 table 的名称,而不检查它们的实际架构,因此,再次注意
  • none 的 tables 已经存在于数据库中:在这种情况下,它像正常迁移一样工作
  • 一些 table 已经存在:你得到一个错误。这是不应该发生的,要么你负责数据库,要么 Django 负责。

请注意,仅当迁移文件的 class 中包含 initial=True 时才会考虑 --fake-initial,否则将忽略该标志。此外,这是 initial=True 在迁移中唯一记录在案的用法。