python – ArrayField中的Django JSONField
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – ArrayField中的Django JSONField,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1674字,纯文字阅读大概需要3分钟。
内容图文
![python – ArrayField中的Django JSONField](/upload/InfoBanner/zyjiaocheng/715/ca24d6aad0204bff9dfba81fc22860bc.jpg)
我在使用带有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?
在极少数情况下,您不需要在该列中进行搜索,并且您不需要使用该列进行连接.
内容总结
以上是互联网集市为您收集整理的python – ArrayField中的Django JSONField全部内容,希望文章能够帮你解决python – ArrayField中的Django JSONField所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。