python - 向现有模型添加字段在 Django 中不起作用

标签 python django sqlite django-models

我已经使用 OneToOneField 和 User-model 创建了自己的模型。现在,我想向该模型添加字段,但是执行 manage.py makemigrationsmigrate 没有看到我对我的 模型所做的任何更改。 py.

models.py:

class UserDetails(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,)
    footsize = models.CharField(max_length=10)
    headsize = models.CharField(max_length=10)

    handsize = models.CharField(max_length=100) #field what I want to add

    def __str__(self):
        return u'%s %s %s' % (self.id, self.footsize, self.headsize)

如果我尝试使用 shell 将值添加到 handsize,则会收到一条错误消息,指出 handsize 字段不存在。有什么问题吗?

最佳答案

我测试了用我的备份做与我的问题相同的事情。执行 makemigrations 时,终端显示此消息:

You are trying to add a non-nullable field 'handsize' to userdetails 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)
 2) Quit, and let me add a default in models.py
Select an option:

我确定,我之前回答过 1),所以这就是该字段未显示在数据库中的原因。所以,现在我回答了 2) 并向该字段添加了默认值:

    handsize = models.CharField(max_length=10, default='40')

现在,migrate 可以正常工作,并将 handsize 作为新字段添加到数据库中。

关于python - 向现有模型添加字段在 Django 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36998520/

相关文章:

python - 向 web2py 表单添加额外的验证要求?

python - 使用重复条目绘制置信区间和预测区间

django - 摘要、基本和承载身份验证

android - 删除主键SQLite后递减外键

sqlite - 将 npm 模块与 Electron 和 webpack 一起使用?

database - 使用应用程序数据库事件写入 AppleScript 2.2 中的 SQLite 文件时

python - 如何将字符串 ['2019-06-01T23:07:02.000+0000' ] 转换为 Python 3 中的日期时间对象

python - Keras BatchNormalization 未初始化值

python - 为什么我的南迁不起作用?

Django:默认语言 i18n