SQLAlchemy ? operator on JSONB key

Viewed 3552

I have a simple table with a JSONB column. In that field I have a key: key and the value of the key can be either a list with ["val1", "val2"] or single string "val2".

I got a raw SQL query that retrieves when a value in key is "val2":

SELECT t.c FROM t WHERE t.c->'key' ? "val2"

However, I am struggling to replicate this in SQLAlchemy query:

I have a session

query = session.query(t).filter(t.c.has_key('val2'))

which results in

SELECT t.c FROM t WHERE t.c ? 'val2' but I want ? operator on ->.

The only way to get -> (as far as I could find) is by using filter(t.c['key2']). However, then I can't perform has_key() I get:

AttributeError: Neither 'JSONElement' object nor 'Comparator' object has an attribute 'has_key'

Any thoughts?

1 Answers
Related