What is the difference between null=True and blank=True in Django?(Django中null=True和blank=True有什么区别?)
问题描述
When we add a database field in django we generally write:
models.CharField(max_length=100, null=True, blank=True)
The same is done with ForeignKey
, DecimalField
etc. What is the basic difference in having
null=True
onlyblank=True
onlynull=True
,blank=True
in respect to different (CharField
, ForeignKey
, ManyToManyField
, DateTimeField
) fields. What are the advantages/disadvantages of using 1/2/3?
null=True
sets NULL
(versus NOT NULL
) on the column in your DB. Blank values for Django field types such as DateTimeField
or ForeignKey
will be stored as NULL
in the DB.
blank
determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True
then the field will not be required, whereas if it's False
the field cannot be blank.
The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL
values for that field. The exception is CharField
s and TextField
s, which in Django are never saved as NULL
. Blank values are stored in the DB as an empty string (''
).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False
if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR
and TEXT
types are never saved as NULL
by Django, so null=True
is unnecessary. However, you can manually set one of these fields to None
to force set it as NULL
. If you have a scenario where that might be necessary, you should still include null=True
.
这篇关于Django中null=True和blank=True有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django中null=True和blank=True有什么区别?
基础教程推荐
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01