前言

在Django项目中,运行$ python manage.py makemigrations $ python manage.py migrate,如果你原来的migrations文件丢失或毁坏,会报各种错误。

解决

最简单的删除migrations目录下非init.py文件,删除数据库,再重新创建。

$ find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
$ find . -path "*/migrations/*.pyc"  -delete

生产环境下,我们不能删除数据库,所以需要重新设置migrations文件。 步骤:

1.从数据库中删除所有非0001_initial的migration history $ DELETE FROM django_migrations WHERE app IN ('core','app') AND name != '0001_initial'

2.运行查看migrations $ python manage.py makemigrations $ python manage.py showmigrations

admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
core
 [X] 0001_initial
 [X] 0002_remove_mymodel_i
 [X] 0003_mymodel_bio
sessions
 [X] 0001_initial

3.使用migrate命令回滚migration history

$ python manage.py migrate --fake core zero
$ python manage.py migrate --fake app zero

$ python manage.py showmigrations #再次show

contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
core
 [ ] 0001_initial
 [ ] 0002_remove_mymodel_i
 [ ] 0003_mymodel_bio
sessions
 [X] 0001_initial

4.删除migrations下的非init.py的文件

$ python manage.py showmigrations

contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
core
 (no migrations)
sessions
 [X] 0001_initial

5.重新创建migrations

$ python manage.py makemigrations

6.在数据库重新生成

$ python manage.py migrate --fake-initial

$ python manage.py showmigrations

contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
core
 [X] 0001_initial
sessions
 [X] 0001_initial

其他问题

django.db.utils.ProgrammingError: column "name" of relation "django_content_type" does not exist
  1. Delete all migrations
  2. Delete records from django_migrations
  3. ALTER TABLE django_content_type ADD COLUMN name character varying(50) NOT NULL DEFAULT ‘someName’;
  4. python manage.py migrate –fake-initial

    django.db.utils.OperationalError: (1050, "Table 'core_user' already exists")
    

python manage.py migrate –fake core

参考

https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html
https://segmentfault.com/a/1190000011594347
http://www.ciika.com/2018/03/django-migrations-fake/
https://stackoverflow.com/questions/30545562/django-column-name-of-relation-django-content-type-does-not-exist
https://stackoverflow.com/questions/25924858/django-1-7-migrate-gets-error-table-already-exists