Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy JSON query rows without a specific key (Key existence)

When using sqlalchemy with postgresql, I have the following table and data:

 id |   data   
----+----------
  1 | {}
  2 | {"a": 1}
(2 rows)

How do I find row(s) that does not have a key. e.g. "a" or data["a"]?

Give me all objects that does not have the key a.
 id |   data   
----+----------
  1 | {}
(1 row)

self.session.query(Json_test).filter(???)
like image 438
AkwMak Avatar asked Mar 10 '23 23:03

AkwMak


1 Answers

If the column type is jsonb you can use has_key:

session.query(Json_test).filter(sqlalchemy.not_(Json_test.data.has_key('a')))

For both json and jsonb types this should work:

session.query(Json_test).filter(Json_test.data.op('->')('a')==None)
like image 67
klin Avatar answered Apr 08 '23 13:04

klin