更新Django模型 [英] Updating django models

查看:42
本文介绍了更新Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在现有模型中添加了一个新字段.当我使用命令"manage.py makemigrations myapp"时,出现以下错误:

I added a new field to an existing model. When I use the command "manage.py makemigrations myapp" I get the following error:

You are trying to add a non-nullable field 'slug' to post without a default. we can not do that < the database needs something to populate existing rows>. 

新字段段塞的默认值应该是什么?这是我的模型:

What should be the default value for the new field slug? Here is my model:

class Post(models.Model):
    title = models.CharField(max_length = 100, null = False, blank = False)
    body = models.TextField()
    dateCreated = models.DateTimeField(default=datetime.now, blank=True)
    slug = models.SlugField(unique = True)

    def __str__(self):
        return self.title

推荐答案

如果没有默认值,则不能将非空字段添加到现有模型中.如果必须将其设置为非空,则应该:

You cannot add a not-null field to an existing model without a default value. If you must make it not-null, you should:

  1. 使用 null = True
  2. 添加字段
  3. 迁移数据库
  4. 填充现有行
  5. 删除 null = True
  6. 再次迁移

这篇关于更新Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆