首页 > 解决方案 > 您正在尝试添加没有默认值的不可空字段库存

问题描述

我在我的模型中添加了一个新字段,但之后我删除了 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 是新增的字段。请注意,其他现有字段都不会引发此错误。

标签: djangodjango-models

解决方案


是否删除数据库文件并不重要。makemigrations 不检查数据库。

如果您将其添加到新模型并进行初始迁移,则只能将不可为空的字段添加到模型中。这是因为,在您进行初始迁移之后,Django 无法知道您是否在其他地方部署了应用程序,因此它无法知道那里是否有模型的实例。这会出错的情况:

  1. 在本地计算机上创建模型 X 并进行迁移。
  2. 将您的 Django 应用程序部署到服务器,其中数据库填充有模型 X 的实例。
  3. 删除本地数据库,将不可为空的字段 Y 添加到模型 X,makemigrations。
  4. 将您的 Django 应用程序部署到服务器。
  5. 出现问题。

这里的解决方案是:

  • 将字段设置为 null=True
  • 为模型添加默认值。
  • 进行迁移时提供默认值。

在您的情况下,我会说提供一次性默认值是可以的,因为听起来您还没有填充数据库。


推荐阅读