在Django models.py中,默认值,null和blank之间有什么区别? [英] In Django models.py, what's the difference between default, null, and blank?

查看:487
本文介绍了在Django models.py中,默认值,null和blank之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

null = True
blank = True
default = 0



有什么区别?何时使用什么?

解决方案

直接从 Django model field reference


code> Field.null



如果 True Django将在数据库中存储空值为 NULL 。默认为 False



请注意,空字符串值总是存储为空字符串,而不是 NULL 。对非字符串字段(如整数,布尔和日期)只能使用 null = True 。对于两种类型的字段,如果您要允许表单中的空值,您还需要设置 blank = True ,如 null 参数只影响数据库存储(参见 blank )。



CharField TextField 之类的基于字符串的字段上,除非有一个很好的原因,否则 。如果基于字符串的字段具有 null = True ,那意味着它对于无数据有两个可能的值:NULL和空字符串。在大多数情况下,对无数据有两个可能的值是多余的:Django约定是使用空字符串,而不是 NULL



Field.blank



如果 True ,则该字段允许为空。默认为 False



注意,这不同于 null null 纯粹是数据库相关的,而 blank 是与验证相关的。如果一个字段 blank = True ,Django的管理网站上的验证将允许输入一个空值。如果字段 blank = False ,则将需要该字段。



Field.default b
$ b

字段的默认值。这可以是值或可调用对象。


你不明白这一切吗?


null=True blank=True default = 0

What's the difference? When do you use what?

解决方案

Direct from 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.

Do you not understand all this?

这篇关于在Django models.py中,默认值,null和blank之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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