django - 当我没有时,Django 认为我有一个 id 字段
问题描述
我创建了以下模型:
class World(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
setting = models.CharField(max_length=200)
creation_date = models.DateTimeField('date created')
当我运行时,manage.py makemigrations
我收到以下错误:
You are trying to add a non-nullable field 'id' to world 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
为什么 Django 认为我有一个 id 字段,我该如何摆脱这个错误?
解决方案
我之前在我的 World 模型中设置了一个 ID 字段,这很令人困惑,因为我删除了它,我添加了以下行:
id = models.AutoField(primary_key=True)
当我再次运行 makemitigrations 时,它询问我是否已将 ID 字段重命名为这个新字段,然后我单击“是”并将其整理出来。
我的模型现在是:
class World(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default='')
name = models.CharField(max_length=200)
setting = models.CharField(max_length=200)
creation_date = models.DateTimeField('date created')
推荐阅读
- sharepoint - SharePoint 快速启动未打开
- python - 如何创建或移动 pg_trgm--1.3.sql 到正确的路径以清除此 SIMILARITY 错误?
- flutter - 如何通过更改对象状态来触发动作?
- python - 如何使用 PyQT5 附加和分离外部应用程序或停靠外部应用程序?
- javascript - 从 API 写入数据时,使用 SQLite3 处理并发的正确方法是什么?
- php - 需要缩短函数输出的文本长度
- python - CSV 中每个字符之间的逗号
- python - 如何下载由 slackbot 创建的文件?
- csv - 如何在 ssis 中的 txt 文件末尾连接 yyyyMMdd?
- php - 在 PHP 中打印多个 sql 语句