SQLAlchemy jsonb 列 - 如何根据键上的 ID 列表执行筛选



我有一个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 谓词一起使用之前,必须强制转换 jsonb 值,就像处理日期时间值一样:

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

最新更新