python - 在 Django 1.9 中,使用 JSONField( native postgres jsonb)的约定是什么?

标签 python json django postgresql jsonb

Django highly suggests notnull=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
    ...
然而,

JSONFieldFalse 覆盖它:

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/

相关文章:

java - Hibernate:运行查询以获取日期范围内的结果时没有结果

python - 将电子邮件重定向到 Python 脚本的最佳方法是什么?

python - Django Rest Framework 中的 API 查询

python - 如何使用分段仿射变换拉直弯曲的文本线/轮廓?

python - 检查目标 : expected activation_2 to have shape (512, 时出错,但得到形状为 (1,) 的数组

android - Gridview - 单击 gridview 项目以在 imageview 中显示图像

python - CSRF token 干扰 TDD - 是否有存储 csrf 输出的变量?

python - 从另一个列表中删除列表列表

python - OpenCV:计算视频中的边界框

javascript - 使用 Ramda 镜头更改多个对象