在Django models.py中,default、null和blank之间有什么区别?

2024-04-26 13:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

  • null=True
  • blank=True
  • default = 0

有什么区别?你什么时候用什么?


Tags: truedefaultnullblank区别
3条回答

直接从Django model field reference

Field.null

If True, Django will store empty values as NULL in the database. Default is False.

Note that empty string values will always get stored as empty strings, not as NULL. Only use null=True for non-string fields such as integers, booleans and dates. For both types of 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).

Avoid using null on string-based fields such as CharField and TextField unless you have an excellent reason. 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;” Django convention is to use the empty string, not NULL.

Field.blank

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, validation on Django’s admin site will allow entry of an empty value. If a field has blank=False, the field will be required.

Field.default

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

我知道你已经有了答案,但是直到今天,还是很难判断是把null=True还是blank=True还是both放到一个字段中。我个人认为,为开发人员提供这么多选择是非常无用和混乱的。让处理空值或空白值。

我按照这张表: When to use null and blank

When to use null and blank

来自docs

null If True, Django will store empty values as NULL in the database. Default is False.

blank If True, the field is allowed to be blank. Default is False.

default The default value for the field.

如果您的代码没有显式地将其设置为值,则可以使用“default”来设置将用于该字段的值。

使用“blank”进行表单验证-blank=True将允许将字段设置为空值

如果要在数据库中将空值存储为“null”,请使用“null”。但是,通常首选将空值设置为空字符串,或者根据给定字段将其设置为0。

相关问题 更多 >