Skip to main content
 首页 » 编程设计

python之在 SQLAlchemy 查询中使用像 substr(X, Y, Z) 这样的 SQL 函数

2025年05月04日25qq号

我不知道如何使用 SQLite 的函数,如 substr(X, Y, Z)使用 SQLAlchemy 的查询表达式语法。我知道我可以使用原始查询,但这会使重用我的 where 子句变得更加困难。这是我的用例:

我有一个文件头表(或模型类),我查询它以识别和列出某些类型的文件。

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' 只是以 ASCII 编码的字符串 Exif 的 SQLite BLOB 文字。实际上,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 实现这个?

请您参考如下方法:

好的。这太简单了。

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