首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Django中,null=True和blank=True有什么区别?

在Django中,null=True和blank=True有什么区别?
EN

Stack Overflow用户
提问于 2011-12-22 20:11:03
回答 28查看 449.3K关注 0票数 1.3K

当我们在Django中添加一个模型字段时,我们通常会写:

代码语言:javascript
运行
复制
models.CharField(max_length=100, null=True, blank=True)

ForeignKeyDecimalField等也是这样做的。两者之间的基本区别是:

  1. 仅限null=True
  2. 仅限blank=True
  3. null=Trueblank=True

对于不同的(CharFieldForeignKeyManyToManyFieldDateTimeField)字段?使用备选方案1、2或3的优缺点是什么?

EN

回答 28

Stack Overflow用户

回答已采纳

发布于 2011-12-22 20:35:26

null=True在DB中的列上设置NULL (相对于NOT NULL)。Django字段类型(如DateTimeFieldForeignKey )的空白值将作为NULL存储在DB中。

blank确定表单中是否需要该字段。这包括管理和您的自定义表单。如果是blank=True,则不需要字段,而如果是False,则字段不能为空。

这两者的组合是如此频繁,因为通常情况下,如果要允许一个字段在表单中为空白,则还需要数据库来允许该字段的NULL值。特例是CharFieldTextField,在Django中,它们从未被保存为NULL。空白值作为空字符串('')存储在DB中。

有几个例子:

代码语言:javascript
运行
复制
models.DateTimeField(blank=True) # raises IntegrityError if blank

models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form

显然,这两个选项使用起来没有逻辑意义(不过,如果您希望在窗体中始终需要一个字段,则null=True, blank=False可能有一个用例,在通过类似的shell处理对象时是可选的)。

代码语言:javascript
运行
复制
models.CharField(blank=True) # No problem, blank is stored as ''

models.CharField(null=True) # NULL allowed, but will never be set as NULL

Django从未将CHARTEXT类型保存为NULL,因此null=True是不必要的。但是,您可以手动将其中一个字段设置为None,以强制将其设置为NULL。如果您有一个可能需要这样做的场景,那么仍然应该包括null=True

票数 1.5K
EN

Stack Overflow用户

发布于 2014-02-16 14:00:00

以下是ORM如何映射Django 1.8的blank & null字段

代码语言:javascript
运行
复制
class Test(models.Model):
    charNull        = models.CharField(max_length=10, null=True)
    charBlank       = models.CharField(max_length=10, blank=True)
    charNullBlank   = models.CharField(max_length=10, null=True, blank=True)

    intNull         = models.IntegerField(null=True)
    intBlank        = models.IntegerField(blank=True)
    intNullBlank    = models.IntegerField(null=True, blank=True)

    dateNull        = models.DateTimeField(null=True)
    dateBlank       = models.DateTimeField(blank=True)
    dateNullBlank   = models.DateTimeField(null=True, blank=True)        

PostgreSQL 9.4创建的数据库字段是:

代码语言:javascript
运行
复制
CREATE TABLE Test (
  id              serial                    NOT NULL,

  "charNull"      character varying(10),
  "charBlank"     character varying(10)     NOT NULL,
  "charNullBlank" character varying(10),

  "intNull"       integer,
  "intBlank"      integer                   NOT NULL,
  "intNullBlank"  integer,

  "dateNull"      timestamp with time zone,
  "dateBlank"     timestamp with time zone  NOT NULL,
  "dateNullBlank" timestamp with time zone,
  CONSTRAINT Test_pkey PRIMARY KEY (id)
)

MySQL 5.6创建的数据库字段是:

代码语言:javascript
运行
复制
CREATE TABLE Test (
     `id`            INT(11)     NOT  NULL    AUTO_INCREMENT,

     `charNull`      VARCHAR(10) NULL DEFAULT NULL,
     `charBlank`     VARCHAR(10) NOT  NULL,
     `charNullBlank` VARCHAR(10) NULL DEFAULT NULL,

     `intNull`       INT(11)     NULL DEFAULT NULL,
     `intBlank`      INT(11)     NOT  NULL,
     `intNullBlank`  INT(11)     NULL DEFAULT NULL,

     `dateNull`      DATETIME    NULL DEFAULT NULL,
     `dateBlank`     DATETIME    NOT  NULL,
     `dateNullBlank` DATETIME    NULL DEFAULT NULL
)
票数 164
EN

Stack Overflow用户

发布于 2017-12-01 09:20:57

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

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

  • null=Falseblank=False:这是默认配置,意味着在所有情况下都需要该值。
  • null=Trueblank=True:这意味着该字段在所有情况下都是可选的。不过,如下文所述,这并不是使基于字符串的字段可选的推荐方法.
  • null=Falseblank=True:这意味着表单不需要值,但是数据库需要。这方面有许多用例:
代码语言:javascript
运行
复制
- The most common use is for optional string-based fields. As [noted in the documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#null), 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.)
代码语言:javascript
运行
复制
- 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`).
代码语言:javascript
运行
复制
- 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](https://stackoverflow.com/a/18244527/2395796). The value of `blank` will still affect forms, though, controlling whether or not validation will succeed when there are no relations.
  • null=Trueblank=False:这意味着表单需要一个值,但数据库不需要。这可能是最常用的配置,但也有一些用例:
代码语言:javascript
运行
复制
- 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.
代码语言:javascript
运行
复制
- Another use case that I've seen is when you have a `ForeignKey` for which you don't wish to allow [cascade deletion](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.on_delete). 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](https://stackoverflow.com/questions/378331/physical-vs-logical-soft-delete-of-database-record).
票数 133
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8609192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档