django - 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 和空字符串都视为没有数据?
解决方案
Django 允许在NULL
基于字符串的字段中使用,建议避免使用。换句话说,Django 按照惯例建议使用''
来表示基于字符串的字段的空值。
此建议的原因是为了避免冗余,因为在大多数情况下,对于基于字符串的字段,两个值 (NULL
和''
) 代表相同的事物。
现在,如果在您的情况下NULL
代表''
不同的事物,那么您应该使用NULL
基于字符串的字段。
因此,不要将“允许”与“建议”混淆。第一个是限制,而另一个是一个好习惯。
推荐阅读
- android-studio - 如何在 Flutter 中解决这个问题?
- java - 如何从后堆栈中删除所有片段并显示新片段
- python - 将熊猫数据框写入 sql 开发人员的问题
- sql-server - SQL Server 替换多个反斜杠
- java - 如何使用arraylist在文件中写入对象
- qt - Raspberry pi 的 Qt:“找不到 DRM 设备!”
- python - 使用多个范围时 Python SymPy 的绘图图例
- python - 创建一个 numpy 二进制网格数组
- python - Keras 自定义损失函数 InvalidArgumentError: In[1] 不是矩阵。相反,它具有形状 []
- xslt-3.0 - XSLT - 递归元数据键控元素