我是django和JSONB的新手,我使用以下语法对JSONB数据字段执行搜索:
obj=SomeModel.objects.filter(data__0__fieldX__contains=search_term)
..它按预期工作。现在,我打印出上述陈述的obj.query
,我得到:
SELECT * FROM "somemodel_some_model"
WHERE ("somemodel_some_model"."data"
#> ['0', 'fieldX']) @> '"some lane"'
但是,当我使用以下内容时执行以上操作:
obj=SomeModel.objects.raw(`query statement above`)
我收到错误:
django.db.utils.ProgrammingError: syntax error at or near "["
LINE 3: #> ['0', 'fieldX']) @> '"some lane"'
我认为我没有逃避“[”,我之前尝试使用反斜杠,但似乎没有帮助。
答案 0 :(得分:0)
你所做的就像是:
with c(j) as (values('
[
{
"fieldX": -20,
"fieldY": 40
},
{
"fieldX":10,
"fieldY": 0
}
]
'::jsonb))
select j #> ['0', 'fieldX'] from c;
ERROR: syntax error at or near "["
LINE 13: select j #> ['0', 'fieldX'] from c;
你需要做的就是像:
t=# with c(j) as (values('
[
{
"fieldX": -20,
"fieldY": 40
},
{
"fieldX":10,
"fieldY": 0
}
]
'::jsonb))
select j #> '{0,fieldX}' from c;
?column?
----------
-20
(1 row)
https://www.postgresql.org/docs/9.5/static/functions-json.html
text[]
是数组,但在Postgres数组中显示为'{}'
或array[]
,而不只是[]
所以
j #> array[0,'fieldX']::text[] from c
也可以使用