如何在SQLAlchemy中查询由JSON列过滤的数据?

时间:2014-12-04 07:57:48

标签: python postgresql sqlalchemy flask-sqlalchemy

我有一个使用flask-SQLAlchmey的烧瓶应用程序。 我有这样的数据库模型

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

...

db = SQLAlchemy()

...

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

数据字段是这样的: [{"type": "a string", "value": "value string"}, {"type": "another", "value": "val"}, ...]

我想查询数据包含{"type": "anything", "value": "what I want"}的所有自定义对象。

2 个答案:

答案 0 :(得分:8)

我使用cast找到了它:

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

答案 1 :(得分:3)

假设您的表名为“custom”且您的json字段名为“data”,则以下sql语句将获得您的结果,其中value子字段等于“我想要的”。

sql = text("select * from custom where data->>'value'= 'what I want'")
result = db.engine.execute(sql)