0

I am quite new to django and JSONB and I use this following syntax to execute a search on JSONB data fields:

obj=SomeModel.objects.filter(data__0__fieldX__contains=search_term)

.. and it works as intended. Now, I print out the obj.query for the above statement and I get:

SELECT * FROM "somemodel_some_model" 
WHERE ("somemodel_some_model"."data"
#> ['0', 'fieldX']) @> '"some lane"'

However, when I excecute the above using:

obj=SomeModel.objects.raw(`query statement above`)

I get an error:

django.db.utils.ProgrammingError: syntax error at or near "["
LINE 3:         #> ['0', 'fieldX']) @> '"some lane"'

I presume I am not escaping the "[", and I have tried using a backslash before, but it does not seem to help.

1 Answer 1

0

what you do is smth like:

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;

what you have to do is smth like:

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[] is array, but in Postgres array are presented as '{}' or array[], not just []

so

 j #> array[0,'fieldX']::text[] from c

would also work

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a tonne for this @Vao - REALLY helps. I have seemed to solve that problem now. I have shamelessly edited the question to ask for another, where, when I use the same logic on a case insensensitive lookup, I get a syntax error near %. It just seems really odd, and I wonder if it is somehow related.
please don't mix posts. just ask a new question
I have now moved it to a new question here and accepted your answer on this: stackoverflow.com/questions/48764138/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.