2014-12-04 686 views
6

我有一個燒瓶應用程序使用flask-SQLAlchmey。 我有一個DB模式這樣如何查詢由SQLAlchemy中的JSON列過濾的數據?

from sqlalchemy.dialects.postgresql import JSON 
from flask.ext.sqlalchemy import SQLAlchemy 

...

db = SQLAlchemy() 

...

class Custom(db.Model): 
    __tablename__ = 'custom' 
    ... 
    data = db.Column(JSON) 
    ... 

數據字段是這樣的: [{"type": "a string", "value": "value string"}, {"type": "another", "value": "val"}, ...]

我想查詢全部定製對象,它們的數據包含{"type": "anything", "value": "what I want"}

回答

7

我發現它使用cast

from sqlalchemy.types import Unicode 
# codes... 
Custom.query.filter(Custom.data['value'].astext.cast(Unicode) == "what I want") 
+1

文檔可以在這裏找到:http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects .postgresql.JSON – Stew 2017-02-28 16:13:44

2

假設你的表名是「custom」,你的json字段被命名爲「data」,下面的sql語句將得到你的結果,其中值子字段等於「我想要的」。

sql = text("select * from custom where data->>'value'= 'what I want'") 
result = db.engine.execute(sql)