ArrayField 中的 Django JSONField [英] Django JSONField inside ArrayField

查看:36
本文介绍了ArrayField 中的 Django JSONField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem inserting to a field using ArrayField with JSONField inside.

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()

当我这样做时,我得到了

When I do this, I got

列位置"是 jsonb[] 类型,但表达式是 text[]

column "locations" is of type jsonb[] but expression is of type text[]

第 1 行:...d"= 2517,位置"= ARRAY['{"loc...

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()

然后我得到了这个

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

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

细节:[";必须引入明确指定的数组维度.

DETAIL: "[" must introduce explicitly-specified array dimensions.

我正在使用:

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

推荐答案

数组

首先,让我们仔细看看这篇来自Postgresql的重要文本数组 文档.

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

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.

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

Most of the time, you should not be using arrays.

JSONB 在 Django 中作为 JSONField 类型可用.该字段比数组字段更具可扩展性和灵活性,并且可以更有效地搜索.但是,如果您发现自己一直在 JSONB 字段中搜索,那么上述关于数组的声明对于 JSONB 同样有效.

JSONB is available in Django as the JSONField type. This field is more scalable and flexible than array fields and can be searched more efficiently. However if you find yourself searching inside JSONB fields all the time the above statement about Arrays is equally valid for JSONB.

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

Now what do you have in your system? A an array that holds JSONB field. This is a disaster waiting to happen. Please normalize your data.

那么什么时候使用ArrayField?

so when to use ArrayField?

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

On the rare occasion when you don't need to search in that column and you don't need to use that column for a join.

这篇关于ArrayField 中的 Django JSONField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆