簡體   English   中英

SqlAlchemy Postgres JSON 如何用問號運算符過濾?

[英]SqlAlchemy Postgres JSON how to filter with question mark operator?

我正在努力將其轉換為 ORM 過濾器查詢:

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

pending_notifications 是一個 JSONB 字段,包含一個簡單的 JSON 數組。

我不確定如何使用問號運算符構建過濾器

我相信 Postgres ARRAY 會像這樣工作:

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

但是我使用的是 JSONB 並且過濾器語法不一樣。

任何建議

您可以使用.op()方法來使用任何逐字操作符:

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

鑒於您使用JSONB作為列數據類型,請使用JSONB has_key()方法:

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

哪個映射到? 運營商。 方法名稱在此上下文中具有誤導性,但jsonb運算符的 PostgreSQL 文檔描述了? 因此:

該字符串是否作為 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

我可以在過濾器中使用原始 sql

from sqlalchemy import text

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM