首页 > 解决方案 > Django为什么只有基于字符串的字段不能有null = true?

问题描述

If True, Django will store empty values as NULL in the database. Default is False.

Avoid using null on string-based fields such as CharField and TextField. 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;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.
For both string-based and non-string-based 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).

-- 来自 django/docs --

我明白为什么基于字符串的字段不允许使用null =true,但是 Integerfield 或其他字段呢?他们也可以有“'nodata'的两个可能值”,对吗?

我了解了 Null 和空字符串之间的区别。为什么 django 不允许对基于字符串的字段同时使用 null 和空白?为什么我们应该将 NULL 和空字符串都视为没有数据?

标签: djangodjango-modelsnullfield

解决方案


Django 允许在NULL基于字符串的字段中使用,建议避免使用。换句话说,Django 按照惯例建议使用''来表示基于字符串的字段的空值。

此建议的原因是为了避免冗余,因为在大多数情况下,对于基于字符串的字段,两个值 (NULL'') 代表相同的事物。

现在,如果在您的情况下NULL代表''不同的事物,那么您应该使用NULL基于字符串的字段。

因此,不要将“允许”与“建议”混淆。第一个是限制,而另一个是一个好习惯。


推荐阅读