我已经使用OneToOneField和User-model创建了自己的模型。现在,我想向该模型添加字段,但是manage.py makemigrations
和migrate
没有看到我对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字段不存在。有什么问题?
答案 0 :(得分: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)回答,所以这就是为什么字段没有显示在数据库中。所以,现在我回答了2)并在字段中添加了默认值:
handsize = models.CharField(max_length=10, default='40')
现在migrate
正常工作,并将handize作为新字段添加到数据库中。
答案 1 :(得分:0)
当您说您已经创建了模型时,我假设您运行了初始迁移。因此,在放入新字段后再次运行迁移时,无法运行全面迁移。您必须在makemigrations之后指定应用程序名称。这样的事情。
./manage.py makemigrations app_name
和
./manage.py migrate.
应该工作。