python - SQLAlchemy jsonb 列 - 如何根据键上的 id 列表执行过滤

标签 python postgresql sqlalchemy jsonb

我有一个 id 列表,例如:

tracker_ids = [69]

我需要根据tracker_id获取所有APInformation对象。

数据如下所示:

{ 'tracker_id' : 69, 'cpu_core_avg': 89.890', 'is_threshold': true,'datetime':1539053379040 }
{ 'tracker_id' : 70, 'cpu_core_avg': 65.0', 'is_threshold': false, 'datetime':1539053379040 }
{ 'tracker_id' : 69, 'cpu_core_avg': 34.9', 'is_threshold': false,'datetime':1539053379040 }

我尝试了以下操作,但出现了错误。

session.query(APInformation).\
    filter(APInformation.data['tracker_id'].in_(tracker_ids),
           APInformation.data['datetime'].astext.cast(BigInteger) > 1539053379040).\
    all()

它抛出的错误:

ProgrammingError: (psycopg2.ProgrammingError) operator does not exist: jsonb = integer
LINE 3: ...oring_apinfomation".data -> 'tracker_id') IN (69)
                                                                ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

最佳答案

您必须先转换 jsonb 值,然后再将其与 IN 谓词一起使用,就像您对 datetime 值所做的那样:

session.query(APInformation).\
    filter(APInformation.data['tracker_id'].astext.cast(Integer).in_(tracker_ids),
           APInformation.data['datetime'].astext.cast(BigInteger) > 1539053379040).\
    all()

关于python - SQLAlchemy jsonb 列 - 如何根据键上的 id 列表执行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712726/

相关文章:

javascript - 如何从 SQLview 接收坐标?开放层 3

python - SQLALchemy:根据列键/名称获取行元素

python - 通过 Paramiko SSH 的 SQLAlchemy

python - Polars - 将列中少于 X 个唯一值的值替换为不同的特定值

Python lxml - 使用 xml :lang attribute to retrieve an element

postgresql - 如何在 PostgreSQL 中模拟死锁?

python - 模型中 django dateTime 的正确格式是什么?

python - 嵌套集模型和 SQLAlchemy——添加新节点

python - FileNotFoundError at/stores/- 将本地 json 文件加载到 Django View 中

python-pip yum 包提供 pip-python 而不是 pip