python - Django 错误 "add a non-nullable field"

标签 python django django-models

当我尝试进行迁移时,出现这样的错误 django 模型:

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

我使用 django 1.8,这是我的模型:

class Person(models.Model):
    user            = models.OneToOneField(User)
    alphanumeric    = RegexValidator(r'^[0-9a-zA-Z]*$', message='hanya yang mengandung karakter alphanumeric')
    email           = models.EmailField(verbose_name='email address', unique=True, max_length=244)
    username        = models.CharField(unique=True, max_length=20, validators=[alphanumeric])
    first_name      = models.CharField(max_length=30, null=True, blank=True)
    last_name       = models.CharField(max_length=30, null=True, blank=True)
    date_of_birth   = models.DateTimeField()
    date_joined     = models.DateTimeField(auto_now_add=True)


    USERNAME_FIELD      = 'username'
    REQUIRED_FIELDS     = ['email']

    def get_full_name(self):
        fullname = self.first_name+" "+self.last_name
        return self.fullname

    def get_short_name(self):
        return self.username

    def list_operator(self):
        return self.operators.all()

    def __str__(self):
        return self.email

class Operator(models.Model):
    person          = models.ForeignKey(Person, related_name="operators", null=True)
    alphanumeric    = RegexValidator(r'^[0-9a-zA-Z]*$', message='hanya yang mengandung karakter alphanumeric')
    email           = models.EmailField(verbose_name='email address', unique=True, max_length=244)
    username        = models.CharField(unique=True, max_length=20, validators=[alphanumeric])
    first_name      = models.CharField(max_length=30, null=True, blank=True)
    last_name       = models.CharField(max_length=30, null=True, blank=True)
    date_of_birth   = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.username;

我想知道我的代码哪里错了。 你能帮我解决这个问题吗?

最佳答案

您的代码没有错。只需按照消息提供的说明操作...

Operator 模型中的 person 字段不能为 null(因为 null=True 不是t 组)。你的数据库中必须已经有 Operators,所以 Django 不知道如何处理这些。

您需要:(a) 在您的模型中提供一个 default 值,(b) 在迁移过程中提供一个默认值,或者 (c) 启用 null该字段的值。

关于python - Django 错误 "add a non-nullable field",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885466/

相关文章:

python - Keras 加载彩色图像

python - 为什么对 dict2 中的嵌套字典的更改会影响 dict1?

django - 如何反向使用DefaultRouter()的URL?

python - Django查询集注释,带有选择的charfield并尝试获取显示值

python - Django:显示 "featured"项目?

python - 如何仅连接字符串中的连续数字?

请解释 Python For 循环和数据类型

python - 我应该如何在 Django 中编写 View 单元测试?

Django - 来自 QuerySet 的唯一列表

python - Django,在某个id之前查询对象