在 Django 的 Movie Model 中定义了主键 movieID,但是执行 数据库迁移的时候,提示以下错误信息:
You are trying to add a non-nullable field 'id' to movie 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
Select an option:
就是 这个字段不能为空因此得有一个默认值,但是又没有预先设置默认值,就会提示这个报错信息。解决办法可以添加一个默认值 default=××× 或者设置该字段允许为空 null=True。但是我想把 movieID 设置为主键,主键不能为空且唯一(UNIQUE),因此都不行。
解决办法是在这个博主的文章中看到的:https://blog.youkuaiyun.com/y16603572192/article/details/87878881
结合自己的情况终于给改好了。总结来就是先注释掉含有不能为空字段的那个 Model 并删除生成的数据库表,然后执行 python manage.py makemigrations 接着执行 python manage.py migrate --fake。再解除注释,重新迁移: python manage.py makemigrations python manage.py migrate ,就成功解决了,并且仍然保持了 movieID 是主键。