django app中的models迁移问题根治方法

今天想给某个app里添加一张表,但是忽略了主键冲突问题,再想改的时候就一直提示

You are trying to add a non-nullable field ‘id’ to sensorconfigalllog without a default; we can’t do that (the database needs something to populate existing rows).
Please select a fix:

  1. Provide a one-off default now (will be set on all existing rows with a null value for this column)
  2. Quit, and let me add a default in models.py

尝试了几种方式都没成功,只能移除迁移记录,重新建表。(这里需要说明的是如果删除记录后,app中其他的表没删,系统会默认所有表都创建了,所以就不会重新建表了。没办法,只能备份好数据,删除所有的表)

具体流程如下:

1.保留data/migrations/init.py,删除其他所有迁移文件;

data为app名称,其他迁移文件建议先备份至别处。

2.清理数据库迁移记录;
DELETE FROM django_migrations WHERE app = 'data';
3.手动删除该应用对应的所有数据库表
DROP TABLE data_sensorconfigalllog;  -- 示例表名,根据实际表名逐一删除
4.重新迁移文件和应用即可
python manage.py makemigrations
python manage.py migrate
5.重新导入备份数据测试

完成!

你可能感兴趣的:(django,django,数据库)