当我们在Django中添加模型字段时,我们通常这样写:

models.CharField(max_length=100, null=True, blank=True)

ForeignKey, DecimalField等也是如此。两者的基本区别是什么:

null = True只 空白= True只 null=True, blank=True

对于不同的(CharField, ForeignKey, ManyToManyField, DateTimeField)字段?使用选项1、2或3的优点/缺点是什么?


当前回答

当你设置null=true时,如果字段没有填充,它将在你的数据库中设置为空。如果 你设置blank=true,它不会为该字段设置任何值。

其他回答

理解Django模型字段定义中的选项(至少)有两个目的是至关重要的:定义数据库表,定义模型表单的默认格式和验证。(我说“默认”是因为可以通过提供自定义表单来覆盖这些值。)一些选项会影响数据库,一些选项会影响表单,还有一些会同时影响两者。

说到null和blank,其他答案已经说明,前者影响数据库表定义,后者影响模型验证。我认为,通过查看所有四种可能配置的用例,可以更清楚地区分它们:

null=False, blank=False: This is the default configuration and means that the value is required in all circumstances. null=True, blank=True: This means that the field is optional in all circumstances. As noted below, though, this is not the recommended way to make string-based fields optional. null=False, blank=True: This means that the form doesn't require a value but the database does. There are a number of use cases for this: The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If NULL was also allowed you would end up with two different ways to indicate a missing value. (If the field is also unique, though, you'll have to use null=True to prevent multiple empty strings from failing the uniqueness check.) Another common situation is that you want to calculate one field automatically based on the value of another (in your save() method, say). You don't want the user to provide the value in a form (hence blank=True), but you do want the database to enforce that a value is always provided (null=False). Another use is when you want to indicate that a ManyToManyField is optional. Because this field is implemented as a separate table rather than a database column, null is meaningless. The value of blank will still affect forms, though, controlling whether or not validation will succeed when there are no relations. null=True, blank=False: This means that the form requires a value but the database doesn't. This may be the most infrequently used configuration, but there are some use cases for it: It's perfectly reasonable to require your users to always include a value even if it's not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data that doesn't need the same stringent validation you want to require of a human editor. Another use case that I've seen is when you have a ForeignKey for which you don't wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False), but if the thing it points to happens to be deleted, you don't want this object to be deleted too. In that case you can use null=True and on_delete=models.SET_NULL to implement a simple kind of soft deletion.

当你说null=False时,这意味着数据必须传递到数据库保存。当你说空白=False时,这意味着数据必须从前端输入,反之亦然

这里,是null=True和blank=True的主要区别:

null和blank的默认值都是False。这两个值都在字段级工作,即,我们是否想要保持字段为空或空白。

null=True将字段的值设置为null,即没有数据。它基本上是为数据库列的值。

date = models.DateTimeField(null=True)

blank=True确定表单中是否需要该字段。这包括管理表单和您自己的自定义表单。

title = models.CharField(blank=True) // title可以为空。 在数据库中(“”)将被存储。 null=True blank=True这意味着该字段在所有情况下都是可选的。

epic = models.ForeignKey(null=True, blank=True)
// The exception is CharFields() and TextFields(), which in Django are never saved as NULL. Blank values a

简单的回答是:Null是数据库表,Blank是Django表单。

在模型中null=True和blank=True的含义还取决于这些字段在表单类中的定义方式。

假设你已经定义了以下类:

class Client (models.Model):
    name = models.CharField (max_length=100, blank=True)
    address = models.CharField (max_length=100, blank=False)

如果表单类是这样定义的:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']
        widgets = {
            'name': forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
            'address': forms.TextInput (attrs = {'class': 'form-control form-control-sm'})
        }

然后,'name'字段将不是强制性的(由于模型中的空白=True), 'address'字段将是强制性的(由于模型中的空白=False)。

然而,如果ClientForm类是这样定义的:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']

    name = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )
    address = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )

然后,这两个字段('name'和'address')将是强制性的,“因为声明式定义的字段保持原样”(https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/),即表单字段的'required'属性的默认值为True,这将要求字段'name'和'address'被填充,即使在模型中,字段已被设置为blank=True。