django - 您正在尝试添加没有默认值的不可空字段库存
问题描述
我在我的模型中添加了一个新字段,但之后我删除了 db.sqlite3(以确保我不会在下面出现错误)
agrawalo@:~/myapp> ls
README.md config core manage.py requirements.txt
但是当我运行 makemigrations 时仍然出现此错误
agrawalo@:~/myapp> ./manage.py makemigrations
You are trying to add a non-nullable field 'high52' to stock 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
class Stock(models.Model):
name = models.CharField(max_length=255)
code = models.CharField(max_length=20, db_index=True)
price = models.DecimalField(max_digits=19, decimal_places=2)
diff = models.DecimalField(max_digits=19, decimal_places=2)
open_price = models.DecimalField(max_digits=19, decimal_places=2)
previous_close = models.DecimalField(max_digits=19, decimal_places=2)
low52 = models.DecimalField(max_digits=19, decimal_places=2)
high52 = models.DecimalField(max_digits=19, decimal_places=2)
last_updated = models.DateTimeField()
objects = DataFrameManager()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
self.last_updated = timezone.now()
return super(Stock, self).save(*args, **kwargs)
def __str__(self):
return str(self.code)
low52 和 high52 是新增的字段。请注意,其他现有字段都不会引发此错误。
解决方案
是否删除数据库文件并不重要。makemigrations 不检查数据库。
如果您将其添加到新模型并进行初始迁移,则只能将不可为空的字段添加到模型中。这是因为,在您进行初始迁移之后,Django 无法知道您是否在其他地方部署了应用程序,因此它无法知道那里是否有模型的实例。这会出错的情况:
- 在本地计算机上创建模型 X 并进行迁移。
- 将您的 Django 应用程序部署到服务器,其中数据库填充有模型 X 的实例。
- 删除本地数据库,将不可为空的字段 Y 添加到模型 X,makemigrations。
- 将您的 Django 应用程序部署到服务器。
- 出现问题。
这里的解决方案是:
- 将字段设置为 null=True
- 为模型添加默认值。
- 进行迁移时提供默认值。
在您的情况下,我会说提供一次性默认值是可以的,因为听起来您还没有填充数据库。
推荐阅读
- javascript - vscode 中的未绑定断点,用于在 docker 容器中调试 nodejs 应用程序
- python - Numpy 300 维数组在字节和缓冲区之后转换为 150 维
- php - 是否可以在 foreach 循环中回显另一个 foreach 数组值?
- javascript - 等待多个文件的文件内容
- linux - 我无法下载 objconv,这是 PATH 问题吗?
- kotlin - 动态扩展循环顶部边框
- msbuild - 错误 MSB3326:无法导入以下密钥文件 XXXXXXSigningKey.snk
- gpu - MPI+OpenACC:#pragma acc host_data use_device() 如何工作?
- python - OOP 项目 - 初学者 - 寻找反馈
- c# - 在 C# 中转换 varchar 值时转换失败