我在使用带有JSONField的ArrayField插入字段时遇到问题.
models.py
locations = ArrayField(JSONField(null = True,blank = True), blank=True, null = True)
插入
location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
instance.locations = location_arr
instance.save()
当我这样做时,我得到了
column “locations” is of type jsonb[] but expression is of type text[]
LINE 1: …d” = 2517, “locations” = ARRAY[‘{“loc…
Hint: You will need to rewrite or cast the expression.
所以我尝试使用以下方式转储它:
import json
location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
instance.locations = json.dumps(location_arr)
instance.save()
然后我得到了这个
LINE 1: …d” = 2517, “locations” = ‘[{“loc”:…
DETAIL: “[” must introduce explicitly-specified array dimensions.
我在用:
> Django 1.9
> Python 2.7
> Postgres 9.4.10
> psycopg2 2.6.2
解决方法:
数组
首先,让我们仔细看看Postgresql Arrays文档中的这个重要文本.
Tip: Arrays are not sets; searching for specific array elements can be
a sign of database misdesign. Consider using a separate table with a
row for each item that would be an array element. This will be easier
to search, and is likely to scale better for a large number of
elements.
大多数情况下,您不应该使用数组.
JSONB
JSONB在Django中可用作JSONField类型.该字段比数组字段更具可伸缩性和灵活性,可以更有效地进行搜索.但是,如果您发现自己一直在JSONB字段内搜索上面关于Arrays的声明对JSONB同样有效.
现在你的系统有什么?一个包含JSONB字段的数组.这是一场等待发生的灾难.请规范化您的数据.
概括
so when to use ArrayField?
在极少数情况下,您不需要在该列中进行搜索,并且您不需要使用该列进行连接.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。