为什么django模型的空白和空白不同的选项? [英] Why are blank and null distinct options for a django model?

查看:190
本文介绍了为什么django模型的空白和空白不同的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django模型中定义字段时,有两种方式可以说该字段是空的。 null 意味着它可以在数据库中为空,而空白表示该表单中的字段可以为空。为什么这些不同?每次我设置一个但不是另一个出了问题。允许它们不同似乎只是邀请形式的问题,允许您创建数据库将不能接受的对象。

When defining fields in a django model, there are two ways to say that the field is allowed to be empty. null means it can be empty in the database, and blank says the field can be empty in a form. Why are these distinct? Every time I set one but not the other something goes wrong. Allowing them to be different seems to be to just inviting problems of the form allowing you to create objects the database won't accept.

换句话说,你什么时候会在django模型中使用 null = True,blank = False null = False,blank = True

In other words, when would you ever use null=True,blank=False or null=False,blank=True in a django model?

推荐答案

他们有两个完全不同的含义:

They have two entirely different meanings:

空白:确定该字段是否应在表单中根据需要进行验证。 False 表示如果不提供,表单将生成错误,而 True 表示允许空值。

blank: determines whether the field should be validated as required or not in forms. False means the form will generate an error if not provide, while True means empty values are allowed.

null :确定该字段是否应设置为 NULL NOT在数据库级别为NULL 。这与表单验证无关。

null: determines whether the field should be set as NULL or NOT NULL at the DB level. This has nothing to do with form validation.

一些示例:

blank = True,null = False 会在字段留空时立即生成 IntegrityError ,如果它不是CharField或TextField。这两个字段在空的时候向数据库发送''(空字符串)而不是 NULL

blank=True, null=False would raise an IntegrityError anytime the field was left blank, if it's not a CharField or TextField. Those two fields send '' (empty string) rather than NULL to the DB when empty.

blank = False,null = True 将始终要求所有表单填写该字段(表单将提高$ code> ValidationError ,即使该列被允许为 NULL 。但是,这仅适用于表格。您可以手动将属性设置为 None 并将其保存在表单外(例如在shell中)。

blank=False, null=True would always require the field to be filled out in all forms (forms will raise ValidationError on the field), even though the column is allowed to be NULL. However, this only applies to forms. You could manually set the attribute to None and save it outside of a form (in the shell, for example).

这篇关于为什么django模型的空白和空白不同的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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