先說結論:
# 假設 JsonField 名稱為 data,內容為 {"info": {"path": "我的資源創建"}}
qs = qs.filter(data__filter={"info.path": "我的資源創建"})
我查看了?tortoise-orm 官方文檔,沒有這方面講述。
問了 gpt4o,一直在兩個錯誤答案之間左右橫跳。
bing搜索,只找到一個使用 CustomFunction 派生類的解決方法。
最后自己看源碼,發現 contrib.mysql.json_functions 內有實現,實現為自定義 operator,使用方法在 tortoise.filters.get_json_filter() 函數內定義:f"{field_name}__filter"
試驗了下列調用方式:
qs.filter(data__filter={"key": "$.info.path", "value": "我的資源創建"}) # ((key, filter_value),) = value.items() 運行錯誤
qs.filter(data__filter={"$.info.path": "我的資源創建"}) # 使用 str(qs.query) 發現多了一個 "$."
最后試出了上面最終的表達式