2016-08-04 218 views
0

我找不出SQLAlchemy的查詢表達式語法如何使用SQLite的substr(X, Y, Z)等函數。我知道我可以使用原始查詢,但這會讓我更難重用where子句。這裏是我的用例:在SQLAlchemy查詢中使用substr(X,Y,Z)等SQL函數

我有一個表格(或模型類)的文件頭,我查詢識別和列出某些類型的文件。

class Blob(Base): 
    __tablename__ = 'blob' 

    _id = Column('_id', INTEGER, primary_key=True) 
    size = Column('size', INTEGER) 
    hash = Column('hash', TEXT) 
    header = Column('header', BLOB) 
    meta = Column('meta', BLOB) 

例如,識別的Exif的圖像,吾人可以用這個原始查詢:

select * from blob where substr(header,7,4) = X'45786966' 

X'45786966'只是SQLite的BLOB字面用於ASCII編碼的字符串Exif。在現實中,where子句更復雜,我想重新使用它們作爲過濾條件加入,大約是這樣的:

# define once at module level 
exif_conditions = [functions.substr(Blob.header, 7, 4) == b'Exif'] 

# reuse for arbitrary queries 
session.query(Blob.hash).filter(*exif_conditions) 
session.query(...).join(...).options(...).filter(condition, *exif_conditions) 

有沒有辦法與SQLAlchemy的實現這一目標?

回答

2

好的。這太簡單了。

from sqlalchemy.sql import func 
exif_conditions = [func.substr(Blob.header, 7, 4) == b'Exif'] 
相關問題