如何在不触及其他应用程序的情况下修复具有现有架构的应用程序的迁移?

How to fix migrations for an app with existing schema while not touching other apps?

Django 1.9.7,db.sqlite3 作为数据库

我有一个包含多个应用程序的 Django 项目。对于应用 "A",我有迁移,但我不小心删除了它们并推送到远程 git。此外,白天还有很多其他应用程序的新内容被推送到 git。其他应用不依赖于 "A" 应用模型。

一切正常,直到我决定向 "A" 应用程序的模型添加一个新字段。我收到 OperationalError: no such column: 错误。我尝试为应用程序 "A" python manage.py migrate --fake-initial 进行初始迁移。我有新的迁移,但我仍然有 OperationalError: no such column:

如何在不影响其他应用迁移的情况下修复 "A" 应用迁移?

git 的角度来看,您可以 revert 到之前的提交。

git revert sha #commit sha of the last commit

git reset --hard HEAD~n #n how many commits to remove.
git push --force

通过 django 修复(如果您以后没有添加任何迁移,则可能。),

python manage.py makemigrations APP_A --empty
python manage.py makemigrations APP_A 
python manage.py migrate --fake

不幸的是git revert没有帮助我。最后,我通过执行以下步骤解决了问题:

1.Manually 删除 db.sqlite3 中与 "A" 应用相关的所有表。

2.Create 来自现有架构的新迁移和 db.sqlite3 表:

python manage.py makemigrations A --empty
python manage.py makemigrations A
python manage.py migrate

3.Dump 表数据从备份返回到 db.sqlite3:

sqlite3 ~/Backup/A/db.sqlite3 ".dump table_name" | grep -v "CREATE" | sqlite3 db.sqlite3