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

标签 python postgresql sqlalchemy flask-sqlalchemy

我正在使用 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": “我想要什么” 在它拥有的对象列表中。

最佳答案

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

from sqlalchemy.types import Unicode

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

关于python - 我如何在 SQLAlchemy 中查询由 JSON 列过滤的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27288903/

相关文章:

python - Azure 存储 Python sdk - get_container_access_policy 不起作用

python - 在 Matplotlib 中创建箱线图均值线和中值线的键

postgresql - Postgres 规则替换 WHERE 子句中的单词

python - SQLAlchemy 选择在 SQLite 表上给出不同的结果,原始 SQL 与可选

mysql - Python 3 和 mysql 通过 SQLAlchemy

python - 类型错误 : cannot unpack non-iterable NoneType object

python - 安装xbpch后Jupyter内核错误

sql - 如何从 ip2location ip 数据库中选择多个 ip 信息?

ruby-on-rails - Rails CSV 导入导致带有前导 0 的数字困惑

python - 将数据从 Pandas 存储到 Snowflake 的最佳方式