Lets say I have a model named Item
, which contains a JSONB field data
. One of the records has the following JSON object stored there:
SQLAlchemy's JSONB type has the contains() method for the @>
operator in Postgresql. The @> operator is used to check if the left value contains the right JSON path/value entries at the top level. In your case
data @> '{"nested_list": [{"nested_key": "one"}]}'::jsonb
Or in python
the_value = 'one'
Session().query(Item).filter(Item.data.contains(
{'nested_list': [{'nested_key': the_value}]}
))
The method converts your python structure to suitable JSON string for the database.
In Postgresql 12 you can use the JSON path functions:
import json
Session().query(Item).\
filter(func.jsonb_path_exists(
Item.data,
'$.nested_list[*].nested_key ? (@ == $val)',
json.dumps({"val": the_value})))