cod*_*kel 1 python sqlite sqlalchemy sql-function
我不知道如何将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)
Run Code Online (Sandbox Code Playgroud)
例如,要识别Exif图像,我可以使用以下原始查询:
select * from blob where substr(header,7,4) = X'45786966'
Run Code Online (Sandbox Code Playgroud)
X'45786966'只是使用ASCII编码BLOB的字符串的SQLite 文字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)
Run Code Online (Sandbox Code Playgroud)
有没有办法用SQLAlchemy做到这一点?
好。这太简单了。
from sqlalchemy.sql import func
exif_conditions = [func.substr(Blob.header, 7, 4) == b'Exif']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2634 次 |
| 最近记录: |