django - 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?
解决方案
我相信你跳过了服务器中的一些迁移,所以现在你缺少一些表(我一直处于这种情况。确保迁移目录在你的.gitignore上。你不能签入迁移文件,你必须makemigrations
在服务器上运行) . 这可以通过回溯到数据库和模型文件匹配的点来解决,但是如果它是您的生产数据库,这是一个有风险的过程,因此您应该在继续之前进行完整备份,然后在另一台计算机上尝试该过程.
这将是我的建议:
- 从服务器中删除迁移文件。
- 评论引起错误的模型。
python manage.py makemigrations
使用and将服务器的迁移历史记录设置为数据库所在的点python manage.py migrate --fake-initial
(这将更新迁移文件而不实际尝试修改数据库)。- 取消注释引发错误的模型。
- 运行
python manage.py makemigrations
和python manage.py migrate
。
如果在您评论引发异常的模型后,您得到了不同的异常,您必须继续评论并再次尝试。迁移成功后,您可以取消注释所有注释模型并进行实际迁移。
推荐阅读
- python - 在while循环执行期间线程停止
- ios - 如何在我的单元格中更改附件类型 -> 披露指示器颜色?
- php - 如何在php或laravel中计算时间差
- c# - C# await delay not working
- excel - 从表格到 Excel 中的 2 列
- hdfs - 如何配置 AWS EMR 以使用 s3 作为 hdfs 存储
- dart - 在 Flutter 应用程序中编辑 MP3/Wav 文件 (Dart)
- php - 我想在 facebook php SDK 中导入 FB 事件数据
- r - 计算数据框列中的元素,然后在 R 中创建单独的列
- java - 调用函数会更新数组吗?