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

查看:66
本文介绍了在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)

ForeignKey DecimalField 等也是如此.

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

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

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

推荐答案

null = True 在数据库中的列.Django字段类型(如 DateTimeField ForeignKey )的空白值将作为 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 = 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 值用于那个领域.例外是 CharField s和 TextField s,它们在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

Django永远不会将

CHAR TEXT 类型保存为 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天全站免登陆