深度阅读

What is the difference between null=True and blank=True in Django Field?

作者
作者
2023年08月22日
更新时间
11.06 分钟
阅读时间
0
阅读量

When we add a model field in Django.

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

What is the basic differences between:

Null=True sets NULL (versus NOT NULL) in your DB.ForeignKey will be stored as NULL in the DB.

The field will be required in forms, if the blank is required.If blank=True then the field will not be required.

The combo of the two is so frequent because typically you’re going to allow a field to be blank in your form.The exception is CharFields and TextFields. They are never saved as NULL in Django.In theDB, the marker values are stored 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

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.However, you can manually set one of these fields to None.If you have a scenario where that might be necessary, you should .

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。