query data filtered by a JSON Column in SQLAlchemy

https://stackoverflow.com/questions/27288903/how-can-i-query-data-filtered-by-a-json-column-in-sqlalchemy

from sqlalchemy.dialects.postgresql import JSON
from flask.ext.sqlalchemy import SQLAlchemy

...

db = SQLAlchemy()

...

class Custom(db.Model):
    __tablename__ = 'custom'
    ...
    data = db.Column(JSON)
    ...

data field are like this: [{"type": "a string", "value": "value string"}, {"type": "another", "value": "val"}, ...]

I want to query all custom objects that their data contain a {"type": "anything", "value": "what I want"}.

##########################answer##################################

from sqlalchemy.types import Unicode
# codes...
Custom.query.filter(Custom.data['value'].astext.cast(Unicode) == "what I want")

Documentation for this can be found here: http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSON

posted @ 2019-12-12 10:22  伊贺双刀流  阅读(132)  评论(0编辑  收藏  举报