Django highly suggests not 将 null=True
用于 CharField 和 TextField 基于字符串的字段,以便没有两个可能的“无数据”值(假设您允许使用空白=真
)。这对我来说很有意义,我在所有项目中都这样做。
Django 1.9 引入 JSONField ,它使用底层 Postgres jsonb
数据类型。上述建议是否适用于 JSONField(即应使用 blank=True
而不是 null=True
)?或者,应该使用 null=True
代替吗?或者,应该使用 default=dict
代替吗?或者, ..?为什么?
换句话说,当您只想允许一个“无数据”值时,新的原生 JSONField 的约定是什么?请支持您的回答,因为我做了很多研究,但找不到任何官方信息。提前致谢。
最佳答案
Django 代码隐含的约定似乎是将空 JSON 值存储为 NULL,而不是空字符串(CharField
的约定也是如此) .我之所以这么说是因为:
empty_strings_allowed
继承自CharField
中的Field
,设置为True
:
django/db/models/fields/__init__.py#L96
class Field(RegisterLookupMixin):
"""Base class for all field types"""
# Designates whether empty strings fundamentally are allowed at the
# database level.
empty_strings_allowed = True
...
然而,JSONField
用 False
覆盖它:
django/contrib/postgres/fields/jsonb.py#L13
class JSONField(Field):
empty_strings_allowed = False
...
这会导致 CharField
在您实例化时默认为 ""
和 JSONField
的默认为 None
没有显式传递这些字段值的模型。
django/db/models/fields/init.py#L791
def get_default(self):
"""
Returns the default value for this field.
"""
if self.has_default():
if callable(self.default):
return self.default()
return self.default
if (not self.empty_strings_allowed or (self.null and
not connection.features.interprets_empty_strings_as_nulls)):
return None
return ""
因此,如果你想让 JSONField
成为可选的,你必须使用:
json_field = JSONField(blank=True, null=True)
如果您只使用 blank=True
,就像您使用 CharField
一样,您将在尝试运行 时收到
没有显式传递 IntegrityError
>MyModel.objects.create(...)json_field
参数。
关于python - 在 Django 1.9 中,使用 JSONField( native postgres jsonb)的约定是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36209336/