簡體   English   中英

如果 JSON 字段包含值,則 SQLAlchemy 過濾

[英]SQLAlchemy filter if JSON field contains a value

我有一張由這個 class 代表的表格

from sqlalchemy import JSON


class Mytable(Base):
    myfield = JSON   

myfield列將包含 JSON arrays。

我想 select 只有myfield列包含特定值foo的行,我該怎么做? (我在 Mysql 8.0 但我認為解決方案可能對所有數據庫類型都相同)

到目前為止我嘗試過的

  • 使用in操作
session.query(Mytable).filter("foo" in Mytable.myfield)

這將返回錯誤NotImplementedError: Operator 'contains' is not supported on this expression

我通過重新運行我認為不起作用的示例找到了答案,並更正了一個錯字:)

通過sqlalchemy.func使用JSON_CONTAINS方法適用於我的情況。

from sqlalchemy import func

session.query(MyTable).filter(func.json_contains(Mytable.myfield, '"foo"', "$"))

(注意foo周圍的雙引號)

暫無
暫無

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

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