在Djang中,向现有模型添加字段不起作用

2024-09-30 16:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用OneToOneField和User model创建了自己的模型。现在,我想将字段添加到该模型中,但是执行manage.py makemigrations和{}没有看到任何更改,这是我对models.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字段不存在。怎么了?在


Tags: py模型selfmodelmanagemodelslengthmax
2条回答

我试着做和我的备份问题一样的事情。终端在执行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),所以这就是为什么field没有显示在数据库中。所以,现在我回答了2)并在字段中添加了默认值:

^{pr2}$

现在,migrate起作用,并将handsize作为一个新字段添加到数据库中。在

当您说您已经创建了模型时,我假设您运行了初始迁移。因此,在放入新字段后再次运行迁移时,不能运行全面迁移。必须在makemigrations之后指定应用程序名称。像这样。在

./manage.py makemigrations app_name

以及

^{pr2}$

应该行得通。在

相关问题 更多 >