栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Django 1.9中,使用JSONField(本地postgres jsonb)的约定是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Django 1.9中,使用JSONField(本地postgres jsonb)的约定是什么?

Django代码隐含的约定似乎是 将JSON空值存储为NULL
而不是空字符串(和的约定一样

CharField
)。我之所以这样说,是因为以下原因:

empty_strings_allowed
从继承
Field
CharField
,并设置为
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
显式传递参数时会得到一个。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669573.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号