SQLAlchemy: filtering on values stored in nested list of the JSONB field

后端 未结 1 615
慢半拍i
慢半拍i 2020-12-03 13:03

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:



        
相关标签:
1条回答
  • 2020-12-03 13:48

    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})))
    
    0 讨论(0)
提交回复
热议问题