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)
)
The following arguments are available to all field types. All are optional.
null
Field.null
If True, Django will store empty values as NULL in the database. Default is False.
Avoid using null on string-based fields such as CharField and
TextField because empty string values will always be stored as empty
strings, not as NULL. If a string-based field has null=True, that
means it has two possible values for "no data": NULL, and the empty
string. In most cases, it’s redundant to have two possible values for
"no data"; the Django convention is to use the empty string, not
NULL.
For both string-based and non-string-based fields, you will also need
to set blank=True if you wish to permit empty values in forms, as
the null parameter only affects database storage (see blank).
Note
When using the Oracle database backend, the value NULL will be stored to denote the empty string regardless of this attribute
null=True
在数据库中的列上设置NULL
(而不是NOT NULL
)。Django字段类型(如DateTimeField
或ForeignKey
)的空值将作为NULL
存储在数据库中。blank=True
确定表单中是否需要该字段。这包括管理员和您自己的自定义表单。如果blank=True
,则不需要该字段,而如果是False
,则该字段不能为空。这两者的组合非常频繁,因为通常如果要允许表单中的某个字段为空,则还需要数据库允许该字段的
NULL
值。例外情况是CharField
s和TextField
s,在Django中,它们是never另存为NULL
。空白值作为空字符串存储在数据库中(''
)。举几个例子:
显然,这两个选项没有逻辑意义(但是,如果您希望表单中始终需要一个字段,那么可能有一个
null=True, blank=False
的用例,但是在通过shell处理对象时是可选的)Django从不将
CHAR
和TEXT
类型保存为NULL
,因此null=True
是不必要的。但是,您可以手动将其中一个字段设置为None
,以强制将其设置为NULL
。如果您有一个可能需要这样做的场景,那么您仍然应该包含null=True
。这就是ORM如何映射Django 1.8的
blank
&;null
字段为PostgreSQL 9.4创建的数据库字段包括:
为MySQL 5.6创建的数据库字段是:
如Django模型字段引用中所述:Link
相关问题 更多 >
编程相关推荐