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

标签 python database django string integer

  • null=True
  • blank=True
  • 默认 = 0

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

最佳答案

直接来自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.

关于python - 在 Django models.py 中,default、null 和 blank 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384098/

相关文章:

python - youtube-dl 完成下载时运行异步函数(python)

java - Java/MySQL 数据库查询结果存储、更新和重用的方法

mysql - 重新插入表记录并更新自增主索引

mysql - 没有主键的数据库表

python - 创建包时,如何管理弱依赖项的迁移?

python - jinja2 模板中的 url 函数在 Django 中抛出 AttributeError

python - 我如何在 Django 中设置我的博客文章的 HTML 格式?

python - SQLAlchemy 关系与 association_proxy 问题

python - 将键盘绑定(bind)添加到现有的 Emacs 模式

python - 如何用 HTML 标记显示文本? (我使用ckeditor)