Python 您正在尝试在没有默认值的情况下向用户配置文件添加不可为空的字段“new_field”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26185687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:11:37  来源:igfitidea点击:

You are trying to add a non-nullable field 'new_field' to userprofile without a default

pythondjango

提问by Irmantas ?elionis

I know that from Django 1.7 I don't need to use South or any other migration system, so I am just using simple command python manage.py makemigrations

我知道从 Django 1.7 我不需要使用 South 或任何其他迁移系统,所以我只是使用简单的命令 python manage.py makemigrations

However, all I get is this error:

但是,我得到的只是这个错误:

You are trying to add a non-nullable field 'new_field' to userprofile without a default;
we can't do that (the database needs something to populate existing rows).

Here is models.py:

这是models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True)
    new_field = models.CharField(max_length=140)

What are options?

什么是选项?

采纳答案by dgel

You need to provide a default value:

您需要提供一个默认值:

new_field = models.CharField(max_length=140, default='SOME STRING')

回答by Alex Carlos

If "website" can be empty than new_fieldshould also be set to be empty.

如果“网站”可以为空,new_field则也应设置为空。

Now if you want to add logic on save where if new_fieldis empty to grab the value from "website" all you need to do is override the save function for your Modellike this:

现在,如果您想在 ifnew_field为空的地方添加逻辑以从“网站”获取值,您需要做的就是覆盖您的保存功能,Model如下所示:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True, default='DEFAULT VALUE')
    new_field = models.CharField(max_length=140, blank=True, default='DEFAULT VALUE')

    def save(self, *args, **kwargs):
        if not self.new_field:
            # Setting the value of new_field with website's value
            self.new_field = self.website

        # Saving the object with the default save() function
        super(UserProfile, self).save(*args, **kwargs)

回答by Tobi

One option is to declare a default value for 'new_field':

一种选择是为 'new_field' 声明一个默认值:

new_field = models.CharField(max_length=140, default='DEFAULT VALUE')

another option is to declare 'new_field' as a nullable field:

另一种选择是将 'new_field' 声明为可空字段:

new_field = models.CharField(max_length=140, null=True)

If you decide to accept 'new_field' as a nullable field you may want to accept 'no input' as valid input for 'new_field'. Then you have to add the blank=Truestatement as well:

如果您决定接受 'new_field' 作为可空字段,您可能希望接受 'no input' 作为 'new_field' 的有效输入。然后你还必须添加blank=True语句:

new_field = models.CharField(max_length=140, blank=True, null=True)

Even with null=Trueand/or blank=Trueyou can add a default value if necessary:

即使使用null=True和/或blank=True您也可以根据需要添加默认值:

new_field = models.CharField(max_length=140, default='DEFAULT VALUE', blank=True, null=True)

回答by gerachev

In new_file add the boolean property null.

在 new_file 中添加布尔属性 null。

new_field = models.CharField(max_length=140, null=True)

after you run a ./manage.py syncdbfor refresh the DB. and finally you run ./manage.py makemigrationsand ./manage.py migrate

运行./manage.py syncdb刷新数据库后。最后你运行./manage.py makemigrations./manage.py migrate

回答by Tomasz

Ifyou are in early development cycle and don't careabout your current database datayou can just remove it and then migrate. But first you need to clean migrations dir and remove its rows from table (django_migrations)

如果您处于早期开发周期并且不关心您当前的数据库数据,您可以将其删除然后迁移。但首先你需要清理迁移目录并从表中删除它的行(django_migrations)

rm  your_app/migrations/*

rm db.sqlite3
python manage.py makemigrations
python manage.py migrate

回答by Arnold Lam

Do you already have database entries in the table UserProfile? If so, when you add new columns the DB doesn't know what to set it to because it can't be NULL. Therefore it asks you what you want to set those fields in the column new_fieldsto. I had to deleteall the rows from this table to solve the problem.

表中是否已有数据库条目UserProfile?如果是这样,当您添加新列时,数据库不知道将其设置为什么,因为它不能是NULL. 因此,它会询问您要将列中的这些字段设置为什么new_fields。我不得不从这个表中删除所有行来解决这个问题。

(I know this was answered some time ago, but I just ran into this problem and this was my solution. Hopefully it will help anyone new that sees this)

(我知道这是前一段时间回答的,但我刚刚遇到了这个问题,这是我的解决方案。希望它会帮助任何看到这个的新人)

回答by Denis Savenko

You can use method from Django Doc from this page https://docs.djangoproject.com/en/1.8/ref/models/fields/#default

您可以从此页面使用 Django Doc 中的方法https://docs.djangoproject.com/en/1.8/ref/models/fields/#default

Create default and use it

创建默认值并使用它

def contact_default():
   return {"email": "[email protected]"}

contact_info = JSONField("ContactInfo", default=contact_default)

回答by Harsh

If you are early into the development cycle you can try this -

如果您处于开发周期的早期,您可以尝试这个 -

Remove/comment that model and all its usages. Apply migrations. That would delete that model and then add the model again, run migrations and you have a clean model with the new field added.

删除/评论该模型及其所有用法。应用迁移。这将删除该模型,然后再次添加该模型,运行迁移,您将拥有一个添加了新字段的干净模型。

回答by Taras Matsyk

What Django actually says is:

Django 实际上是这样说的:

Userprofile table has data in it and there might be new_fieldvalues which are null, but I do not know, so are you sure you want to mark property as non nullable, because if you do you might get an error if there are values with NULL

Userprofile 表中有数据,可能有new_field值为空的值,但我不知道,所以您确定要将属性标记为不可为空,因为如果这样做,如果存在值为 NULL 的值,您可能会收到错误

If you are sure that none of values in the userprofiletable are NULL - fell free and ignore the warning.

如果您确定userprofile表中的值都不是 NULL - 自由并忽略警告。

The best practice in such cases would be to create a RunPython migration to handle empty values as it states in option 2

在这种情况下的最佳实践是创建一个 RunPython 迁移来处理选项 2 中所述的空值

2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)

2) 暂时忽略,让我自己处理带有 NULL 的现有行(例如,因为您在之前的数据迁移中添加了 RunPython 或 RunSQL 操作来处理 NULL 值)

In RunPython migration you have to find all UserProfileinstances with empty new_fieldvalue and put a correct value there (or a default value as Django asks you to set in the model). You will get something like this:

在 RunPython 迁移中,您必须找到所有UserProfile具有空new_field值的实例并在其中放置一个正确的值(或 Django 要求您在模型中设置的默认值)。你会得到这样的东西:

# please keep in mind that new_value can be an empty string. You decide whether it is a correct value.
for profile in UserProfile.objects.filter(new_value__isnull=True).iterator():
    profile.new_value = calculate_value(profile)
    profile.save() # better to use batch save

Have fun!

玩得开心!

回答by Josh

I honestly fount the best way to get around this was to just create another model with all the fields that you require and named slightly different. Run migrations. Delete unused model and run migrations again. Voila.

老实说,我发现解决这个问题的最好方法是创建另一个模型,其中包含您需要的所有字段,并且名称略有不同。运行迁移。删除未使用的模型并再次运行迁移。瞧。