[英]Django JSONField inside ArrayField
我在使用带有 JSONField 的 ArrayField 插入字段时遇到问题。
模型.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()
当我这样做时,我得到了
列“位置”的类型为 jsonb[] 但表达式的类型为 text[]
第 1 行:...d" = 2517, "locations" = ARRAY['{"loc...
提示:您需要重写或转换表达式。
所以我尝试使用以下方法转储它:
import json
location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
instance.locations = json.dumps(location_arr)
instance.save()
然后我得到了这个
第 1 行:...d" = 2517, "locations" = '[{"loc":...
详细信息:“[”必须引入明确指定的数组维度。
我在用:
首先,让我们仔细看看这篇来自Postgresql Arrays文档的重要文本。
提示:数组不是集合; 搜索特定的数组元素可能是数据库设计错误的标志。 考虑使用一个单独的表格,其中每个项目都有一行,这将是一个数组元素。 这将更容易搜索,并且可能对大量元素进行更好的缩放。
大多数时候,您不应该使用数组。
JSONB 在 Django 中作为 JSONField 类型可用。 该字段比数组字段更具可扩展性和灵活性,并且可以更有效地搜索。 但是,如果您发现自己一直在 JSONB 字段中搜索,那么上述关于数组的声明对于 JSONB 同样有效。
现在你的系统里有什么? 一个包含 JSONB 字段的数组。 这是一场等待发生的灾难。 请规范化您的数据。
那么什么时候使用 ArrayField 呢?
在极少数情况下,您不需要在该列中搜索并且不需要使用该列进行联接。
我遇到过同样的情况。 这是我解决它的方法
模型.py
from django.contrib.postgres.fields.jsonb import JSONField as JSONBField
location = JSONBField(default=list,null=True,blank=True)
插入
model_object.location = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
更新
model_object.location.append({"locations" : "loc1","amount":Decimal(100.00)})
model_object.save()
这在 Django 中对我有用 - 2.0.2 Postgres - 9.5 psycopg2 - 2.7.4 python - 3.4.3
您可以通过使用 JSONField 作为列字段类型以list
作为根元素来回避这个问题。
from django.contrib.postgres.fields import JSONField
class MyDBArray(models.Model):
array_data = models.JSONField(default=list)
my_db_array = MyDBArray(array_data=[1, 2, 3])
my_db_array.save()
您需要在save
方法中验证array_data
字段实际上是类似列表的。
我想最简单的方法是将字段从 jsonfield 数组转换为 jsonfield。 只需向 location_arr 添加一个键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.