小编典典

ArrayField内的Django JSONField

django

我在使用带有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.`

我在用:

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

阅读 1044

收藏
2020-03-26

共1个答案

小编典典

数组
首先,让我们仔细看看Postgresql Arrays文档中的这一重要文本。

提示:数组不是集合;搜索特定的数组元素可能是数据库设计错误的标志。考虑使用单独的表,该表的每个行都将是一个数组元素。这将更易于搜索,并且可能会针对大量元素进行更好地缩放。

大多数时候,你不应该使用数组。

JSONB
JSONB在Django中可用作JSONField类型。该字段比数组字段更具可伸缩性和灵活性,并且可以更高效地进行搜索。但是,如果你发现自己一直在JSONB字段中进行搜索,则上述有关数组的声明对JSONB同样有效。

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

概括
那么什么时候使用ArrayField?

在极少数情况下,你不需要在该列中进行搜索,也不需要使用该列进行联接。

2020-03-26