Python SQLAlchemy and Postgres - How to query a JSON element

后端 未结 4 422
-上瘾入骨i
-上瘾入骨i 2021-02-05 02:04

Let\'s say I have a Postgres database (9.3) and there is a table called Resources. In the Resources table I have the fields id which is an

相关标签:
4条回答
  • 2021-02-05 02:12

    If you are using JSON type (not JSONB) the following worked for me:

    Note the '"object"'

        query = db.session.query(ProductSchema).filter(
            cast(ProductSchema.ProductJSON["type"], db.String) != '"object"'
        )
    
    0 讨论(0)
  • 2021-02-05 02:14

    According sqlalchemy.types.JSON, you can do it like this

    from sqlalchemy import JSON
    from sqlalchemy import cast
    records = db_session.query(Resource).filter(Resources.data["lastname"] == cast("Doe", JSON)).all()
    
    0 讨论(0)
  • 2021-02-05 02:25

    Also you could explicitly cast string to JSON (see Postgres JSON type doc).

    from sqlalchemy.dialects.postgres import JSON
    from sqlalchemy.sql.expression import cast
    db_session.query(Resource).filter(
        Resources.data["lastname"] == cast("Doe", JSON)
    ).all()
    
    0 讨论(0)
  • 2021-02-05 02:31

    Try using astext

    records = db_session.query(Resource).filter(
                  Resources.data["lastname"].astext == "Doe"
              ).all()
    

    Please note that the column MUST have a type of a JSONB. The regular JSON column will not work.

    0 讨论(0)
提交回复
热议问题