ArrayField中的Django JSONField

ald*_*ido 14 python arrays django postgresql json

我在使用带有JSONField的ArrayField插入字段时遇到问题.

models.py

locations = ArrayField(JSONField(null = True,blank = True), blank=True, null = True)
Run Code Online (Sandbox Code Playgroud)

插入

location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
instance.locations = location_arr
instance.save()
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到了

列"locations"的类型为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()
Run Code Online (Sandbox Code Playgroud)

然后我得到了这个

第1行:...... d"= 2517,"locations"='[{"loc":......

详细信息:"["必须引入显式指定的数组维度.

我在用:

  1. Django 1.9
  2. Python 2.7
  3. Postgres 9.4.10
  4. psycopg2 2.6.2

e4c*_*4c5 14

数组

首先,让我们仔细看看Postgresql Arrays文档中的这个重要文本.

提示:数组不是集合; 搜索特定的数组元素可能是数据库错误设计的标志.考虑为每个将成为数组元素的项使用一个单独的表.这将更容易搜索,并且可能更好地扩展到大量元素.

大多数情况下,您不应该使用数组.

JSONB

JSONB在Django中可用作JSONField类型.该字段比数组字段更具可伸缩性和灵活性,可以更有效地进行搜索.但是,如果您发现自己一直在JSONB字段内搜索上面关于Arrays的声明对JSONB同样有效.

现在你的系统有什么?一个包含JSONB字段的数组.这是一场等待发生的灾难.请规范化您的数据.

概括

那么什么时候使用ArrayField?

在极少数情况下,您不需要在该列中进行搜索,并且您不需要使用该列进行连接.


Sat*_*mar 6

我遇到过同样的情况。这是我解决它的方法

模型.py

from django.contrib.postgres.fields.jsonb import JSONField as JSONBField
location = JSONBField(default=list,null=True,blank=True)
Run Code Online (Sandbox Code Playgroud)

插入

model_object.location = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
Run Code Online (Sandbox Code Playgroud)

更新

model_object.location.append({"locations" : "loc1","amount":Decimal(100.00)})
model_object.save()
Run Code Online (Sandbox Code Playgroud)

这在 Django 中对我有用 - 2.0.2 Postgres - 9.5 psycopg2 - 2.7.4 python - 3.4.3