【问题标题】:how can i query data filtered by a JSON Column in SQLAlchemy?如何在 SQLAlchemy 中查询由 JSON 列过滤的数据?
【发布时间】:2015-02-02 00:43:33
【问题描述】:

我正在使用 Flask 和 flask-SQLAlchemy 编写一个应用程序。

我有一个models.py 文件如下

from sqlalchemy.dialects.postgresql import JSON

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

    data = db.Column(JSON)

data 字段的值是这样的:

[
    {"type": "a string", "value": "value string"},
    {"type": "another", "value": "val"},
    ...
]

现在我想查询所有Custom 对象,它们的data 字段在其拥有的对象列表中包含类似{"type": "anything", "value": "what I want"} 的对象。

【问题讨论】:

    标签: python postgresql sqlalchemy flask-sqlalchemy


    【解决方案1】:

    根据documentation,可以使用cast完成:

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

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-09
      • 2015-03-31
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 2015-05-11
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多