如何在sqlalchemy表达式语言中使用jsonb与select表达式中的整数进行比较?

时间:2019-07-16 11:46:41

标签: python postgresql sqlalchemy

如何使用sqlalchemy核心表达式语言访问jsonb词典值?例如:

 s1 = select([issues.c.id,
             issues.c.data['product_id'],
             products.c.name.label('product_name')
             ]). \
    where(issues.c.id == issue_id). \
    select_from(issues.
    outerjoin(products,
    (issues.c.data['product_id']).cast(Integer) == (products.c.id)))

问题表中存储的数据如下:

id    | data------+
5247  | {"priority": "M", "product_id": "1"}

我究竟如何使用此表达式来联接表。上面的错误为:sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: jsonb = integer

1 个答案:

答案 0 :(得分:1)

通过在转换为整数之前添加astext来获得它:

s1 = select([issues.c.id,
             issues.c.data['product_id'],
             products.c.name.label('product_name')
             ]). \
    where(issues.c.id == issue_id). \
    select_from(issues.
    outerjoin(products,
    (issues.c.data['product_id']).astext.cast(Integer) == (products.c.id)))