Django highly suggests not to use null=True for CharField and TextField string-based fields in order not to have two possible values for "no data" (assuming you're allowing empty strings with blank=True). This makes total sense to me and I do this in all my projects.

Django 1.9 introduces JSONField, which uses the underlying Postgres jsonb data type. Does the suggestion above carry over to JSONField (i.e. blank=True should be used instead of null=True)? Or, should null=True be used instead? Or, should default=dict be used instead? Or, ..? Why?

In other words, what is the convention for the new native JSONField, when you want to allow only one "no data" value? Please support your answer because I did a lot of research and couldn't find anything official. Thanks in advance.

推荐答案

The convention implied from the Django code seems to be to store null JSON values as NULL as opposed to as an empty string (as is the convention for the CharField). I say this because of the following:

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, however, overrides it with 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 ""

因此,如果你想 Select JSONField,你必须使用:

json_field = JSONField(blank=True, null=True)

如果您只使用blank=True,就像您在CharField中使用的那样,那么在try 运行MyModel.objects.create(...)而不显式传递json_field参数时,您将得到IntegrityError.

Json相关问答推荐

jq不会为空输入返回非零

您可以使用Jolt对JSON执行OR条件吗

在PowerShell中,如何获取数据对所在的JSON对象的名称

Vegalite中分组条形图中的偏移量问题

织女星-没有循环的动画条形图第二部分(实际上是织女星)

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

为什么 Django Rest API 序列化器没有正确序列化多对多字段

爆炸没有数组的 struct pyspark

将带有::text[]的JSON数组转换未按预期工作

shell解析json并循环输出组合变量

boost::json::value 的大括号初始化将其从对象转换为数组

Powershell JSON 操作

C# 合并 2 个几乎相同的 JSON 对象

如何使用 Swiftui 判断 JSON 是否缺少键值对

如何在不解析的情况下在javascript中同步包含JSON数据?

Qt使用QJsonDocument、QJsonObject、QJsonArray解析JSON

将错误消息作为 JSON 对象发送

如何将 LinkedTreeMap 转换为 gson JsonObject

Jackson 没有使用 @JsonProperty 覆盖 Getter

为什么 RestTemplate 不将响应表示绑定到 PagedResources?