Django You are trying to add a non-nullable field 'test' to workbook without a default; we can't do that (the database needs something to populate existing rows). Please select a fix

Original
2021-02-07 / 0 评论 / 3 阅读 / 正在检测是否收录...

操作

Django修改业务模型后makemigrations时出现上述报错
Django3.1.6
原model

class WorkBook(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    holder = models.CharField(max_length=30)
    company = models.CharField(max_length=50)
    description = models.CharField(max_length=255)
    createTime = models.DateTimeField(auto_now_add=True)
    flag = models.IntegerField(default=0)

    def __str__(self):
        return self.title

新增一个字段

class WorkBook(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    holder = models.CharField(max_length=30)
    company = models.CharField(max_length=50)
    description = models.CharField(max_length=255)
    test = models.CharField(max_length=30) # 增加这一行
    createTime = models.DateTimeField(auto_now_add=True)
    flag = models.IntegerField(default=0)

    def __str__(self):
        return self.title

新增test字段后,shell执行makemigrations动作后提示

You are trying to add a non-nullable field 'test' to workbook 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

解决方案

在模型中将字段增加任意default值,即

test = models.CharField(max_length=30, default='o')

然后shell执行makemigrations,再执行migrate

再将模型中的default删掉,即

test = models.CharField(max_length=30)

然后shell执行makemigrations,再执行migrate

0

评论 (0)

取消