Django踩坑:数据迁移遇到的问题

问题描述

  在学习过程中我在同一个APP(名为’tst’)下反复修改模型(注释旧的模型,创建新的模型),在创建新模型后尝试进行数据迁移,出现如下错误信息:

1
No migrations to apply

  在尝试从数据库中删除所有与tst相关的字段后再次尝试迁移:

1
1050, "Table 'django_content_type' already exists"

原因分析

  造成多次应用migrations失败的原因是,当前model是修改过的,原来的migrations已经被我删除,但是,重新生成的migrations使用递增整数记名,所以,在django_migrations表中0001,0002等前面几个数字的文件都已被记录,在Django看来,被记录了就相当于已应用,所以,会出现刚开始的No migrations to apply.

解决方案

  python manage.py migrate —fake-initial
  python manage.py makemigrations
  python manage.py migrate

关于—fake-initial和—fake

—fake-initial

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 and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.

—fake

Marks the migrations up to the target one (following the rules above) as applied, 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.

引用参考

cdsn
Django2.0官方文档