Django 中的 null=True 和 blank=True 有什么区别? [英] What is the difference between null=True and blank=True in Django?

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

问题描述

我们在django中添加数据库字段的时候一般这样写:

When we add a database field in django we generally write:

models.CharField(max_length=100, null=True, blank=True)

ForeignKeyDecimalField 等也是如此.

  1. null=True
  2. blank=True
  3. null=True, blank=True
  1. null=True only
  2. blank=True only
  3. null=True, blank=True

关于不同的(CharFieldForeignKeyManyToManyFieldDateTimeField)字段.使用 1/2/3 的优点/缺点是什么?

in respect to different (CharField, ForeignKey, ManyToManyField, DateTimeField) fields. What are the advantages/disadvantages of using 1/2/3?

推荐答案

null=True 设置 NULL(相对于 NOT NULL)您的数据库中的列.DateTimeFieldForeignKey 等 Django 字段类型的空白值将在数据库中存储为 NULL.

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 确定表单中是否需要该字段.这包括管理员和您的自定义表单.如果 blank=True 则不需要该字段,如果是 False 则该字段不能为空.

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.

两者的组合如此频繁,因为通常如果您要允许表单中的字段为空,您还需要数据库允许 NULL 值那个领域.例外是 CharFields 和 TextFields,它们在 Django 中从不保存为 NULL.空值作为空字符串 ('') 存储在数据库中.

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 CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string ('').

几个例子:

models.DateTimeField(blank=True) # raises IntegrityError if blank

models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form

显然,这两个选项的使用没有逻辑意义(尽管如果您希望表单中始终需要某个字段,则 null=True, blank=False 可能有一个用例, 在通过 shell 之类的东西处理对象时可选.)

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

CHARTEXT 类型永远不会被 Django 保存为 NULL,所以 null=True 是不必要的.但是,您可以手动将这些字段之一设置为 None 以强制将其设置为 NULL.如果您有可能需要这样做的场景,您仍应包含 null=True.

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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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