【问题标题】:SqlAlchemy Postgres JSON how to filter with question mark operator?SqlAlchemy Postgres JSON如何用问号运算符过滤?
【发布时间】:2020-07-14 14:06:45
【问题描述】:

我正在努力将其转换为 ORM 过滤器查询:

select count(*) from issues WHERE pending_notifications ? 'flooby';

pending_notifications 是一个 JSONB 字段,包含一个简单的 JSON 数组。

我不确定如何使用问号运算符构造过滤器

我相信 Postgres ARRAY 会像这样工作:

query.filter(pending_notifications.any('flooby'))

但是我用的是JSONB,过滤器语法不一样。

任何建议

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    您可以使用.op() 方法来使用任何逐字运算符:

    query.filter(pending_notifications.op("?")("flooby"))
    

    【讨论】:

      【解决方案2】:

      鉴于您使用JSONB 作为列数据类型,请使用has_key() 方法:

      query.filter(pending_notifications.has_key('flooby'))
      

      映射到? 运算符。在这种情况下,方法名称具有误导性,但 PostgreSQL documentation for jsonb operators 如此描述 ?

      字符串是否作为顶级键存在于 JSON 值中?

      所以has_key() 的名字有点贴切。

      一个例子:

      In [21]: t = Table('t', metadata, Column('json', postgresql.JSONB))
      
      In [28]: print(t.c.json.has_key('test'))
      t.json ? :json_1
      

      【讨论】:

        【解决方案3】:

        我可以在过滤器中使用原始 sql

        from sqlalchemy import text
        
        db.session.query(Issue).filter(text("pending_notifications ? 'flooby'")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-06-01
          • 2023-03-15
          • 1970-01-01
          • 2016-11-17
          • 2014-06-25
          • 2021-12-27
          • 2021-08-08
          相关资源
          最近更新 更多