how can i query data filtered by a JSON Column in SQLAlchemy?

flask-sqlalchemy, postgresql, python, sqlalchemy

Solution

According to the documentation, it can be done using `cast`:

from sqlalchemy.types import Unicode

Custom.query.filter(Custom.data['value'].astext.cast(Unicode) == "what I want")

Problem

I'm writing an app using Flask and flask-SQLAlchemy. I have a `models.py` file as follow ``` from sqlalchemy.dialects.postgresql import JSON class Custom(db.Model): __tablename__ = 'custom' data = db.Column(JSON) ``` `data` field's value would be like this: ``` [ {"type": "a string", "value": "value string"}, {"type": "another", "value": "val"}, ... ] ``` Now I want to query all `Custom` objects that their `data` field contains an object like this `{"type": "anything", "value": "what I want"}` in the list of objects it has.

Original source

Related problems