即使需要字段也创建对象 [英] object created even if field was required

查看:81
本文介绍了即使需要字段也创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#models.py

class Mymodel(models.Model):
    name = models.CharField(max_length=100,null=False,blank=False)
    email = models.EmailField(max_length=100,null=False,blank=False)
    password = models.CharField(max_length=120,null=False,blank=False)
    email_notification = models.BooleanField()




#views.py

obj=MyModel.objects.create(name="ok",password="dsfdsfdsfdsfsfds",email_notification=1)

即使需要电子邮件字段,那么当我在管理面板中看到该对象时,也创建了对象。这可能是问题所在,为什么即使电子邮件字段为必填,也为什么创建了对象?
另外,如果我进入管理面板并打开该对象,然后单击保存,那么它将引发需要电子邮件的情况。

even if email was required field,then also object was created when I see in the admin panel.What can be the issue,Why object got created,even if email field was mandatory? Also if I go in admin panel and open that object and click save then it raises that email is required

推荐答案

注意:您不必在字段中提供null = False,blank = False,因为这些是默认使用的值。(请参阅 Django Field __ int __ 签名。)。

Note: You don't to have provide null=False,blank=False in your fields because those are the values used by default.(See the Django Field __int__ signature.).

def __init__(self, verbose_name=None, name=None, primary_key=False,
                 max_length=None, unique=False, blank=False, null=False,
                 db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
                 serialize=True, unique_for_date=None, unique_for_month=None,
                 unique_for_year=None, choices=None, help_text='', db_column=None,
                 db_tablespace=None, auto_created=False, validators=(),
                 error_messages=None):

默认情况下,数据库中的所有字段均使用 NOT NULL 约束。 如果为特定字段设置 null = True ,则django在数据库的列中设置 NULL 与Python的关键字等效。

By default all the fields in database are created with NOT NULL constraint. If you set null=True for a particular field, then django sets NULL on the column in your DB. It’s the database equivalent of Python’s None keyword.

带有 null 参数

假定我具有以下 Mymodel 在我的 my_app 中,我将 email 字段设置为 null = True

Assume that I have the following Mymodel in my my_app and I set email field to null=True.

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100, null=True)
    password = models.CharField(max_length=120)
    email_notification = models.BooleanField()

在Shell中,

>> from my_app.models import MyModel

>> new = MyModel.objects.create(name="ok",
                                password="dsfdsfdsfdsfsfds",
                                email_notification=1)
>> new.email == None
>> True # As you can see Django sets db value 
        # as NULL and when we query the data it converts back to Python `None` object.

不带 null 参数的示例

假设我的 my_app Mymodel $ c>。(请记住,默认情况下 null False

Assume that I have the following Mymodel in my my_app.(remember null will be False by default)

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=120)
    email_notification = models.BooleanField()

在Shell中,

>> from my_app.models import MyModel
>> new_obj = MyModel.objects.create(name="test",
                                password="test",
                                email_notification=1)
>> new_obj.email == ''
>> True

即, Django CharField TextField 的默认值作为空字符串('')存储在数据库中。换句话说,如果您在不提供 CharField (或 TextField )值的情况下创建对象,那么Django调用 get_default 方法并返回''(仅在这种情况下)。此值将存储在数据库中。

Ie,Django CharField and TextField the default values are stored in the DB as an empty string (''). In other words, if you create an object without providing values for a CharField(or a TextField) under the hood Django invokes the get_default method and returns '' (only in this case). This value will be stored in the database.

以下是 get_default 方法。

The following is the source code of get_default method.

def get_default(self):
    """Return the default value for this field."""
    return self._get_default()

@cached_property
def _get_default(self):
    if self.has_default():
        if callable(self.default):
            return self.default
        return lambda: self.default

    if not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls:
        return return_None
    return str  # return empty string

让我们回答您的问题:


为什么创建对象,即使电子邮件字段是必需的?

Why object got created,even if email field was mandatory?

答案是 EmailField CharField 的一个实例,因此,在创建广告时,将使用默认值''数据库中的对象。这就是为什么您没有得到 django.db.utils.IntegrityError

The answer is EmailField is an instance of CharField Hence default value '' will be used while creating an object in database. That is why you are not getting django.db.utils.IntegrityError.

>> new_obj = Mymodel.objects.create(name='tes1t', password='test1', email_notification=1)
>>> new_obj.email
''



此外,如果我转到管理面板并打开该对象并单击保存,然后单击
,它将引发错误,指示需要电子邮件

Also if I go to the admin panel and open that object and click save then it raises an error indicating that email is required

记住空白 null 不同。 null 纯粹与数据库有关,而空白与验证有关。 因此,当您直接使用Python代码创建对象或自行执行原始SQL时,实际上您会绕过Django的所有输入验证。但是,在admin中,Django会通过模型表单来验证输入。由于在您的情况下空白设置为False(不允许空白),因此模型表格将引发需要电子邮件错误。

Remember blank is different from null. null is purely database-related, whereas blank is validation-related. So when you create an object directly in Python code, or execute raw SQL yourself, you are actually bypassing all of Django’s input validation. But in admin, Django is validating the input through the model form. Since in your case blank is set to False(blank not allowed), model form will raise Email is required Error.

以下是空白参数的相关Django文档。

Here is the relevant Django documentation for blank argument.


Field.blank

Field.blank

如果为True,则允许该字段为空白。默认值为False。注意
这与null不同。 null仅与数据库相关,
,而空白与验证相关。如果字段为blank = True,则表单
验证将允许输入空值。如果字段中有
blank = False,则必须填写该字段。

If True, the field is allowed to be blank. Default is False. Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.

其他资源

  • Django tips: the difference between ‘blank’ and ‘null’
  • differentiate null=True, blank=True in django

这篇关于即使需要字段也创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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