首页 > 解决方案 > Django migrate fails when creating new table

问题描述

We are fairly new to Django. We we have an app and a model. We'd like to add an 'Category' object to our model. We did that, and then ran 'python manage.py makemigrations'.

We then deploy our code to a server running the older code, and run 'python manage.py migrate'. This throws 2 pages of exceptions, finishing with 'django.db.utils.ProgrammingError: (1146, "Table 'reporting.contact_category' doesn't exist")'

This seems to be looking at our models.py. If we comment out Category from our model, and all references to it, the migration succeeds.

I thought that the point of migrations is to make the database match what the model expects, but this seems to require that the model match the database before the migration.

We clearly are doing something wrong, but what?

标签: djangodjango-models

解决方案


我相信你跳过了服务器中的一些迁移,所以现在你缺少一些表(我一直处于这种情况。确保迁移目录在你的.gitignore上。你不能签入迁移文件,你必须makemigrations 在服务器上运行) . 这可以通过回溯到数据库和模型文件匹配的点来解决,但是如果它是您的生产数据库,这是一个有风险的过程,因此您应该在继续之前进行完整备份,然后在另一台计算机上尝试该过程.

这将是我的建议:

  1. 从服务器中删除迁移文件。
  2. 评论引起错误的模型。
  3. python manage.py makemigrations使用and将服务器的迁移历史记录设置为数据库所在的点python manage.py migrate --fake-initial(这将更新迁移文件而不实际尝试修改数据库)。
  4. 取消注释引发错误的模型。
  5. 运行python manage.py makemigrationspython manage.py migrate

如果在您评论引发异常的模型后,您得到了不同的异常,您必须继续评论并再次尝试。迁移成功后,您可以取消注释所有注释模型并进行实际迁移。


推荐阅读