来自docs的示例,但无法理解为什么它不起作用
class CCStandard(Base):
"""Codes, grade, code description, and name"""
__tablename__ = "DimCCStandard"
CCStandardKey = deferred(Column('CCStandardKey', Integer, primary_key=True))
CCStdCode = Column('CCStdCode', String)
#ccstd_info group
CCStdDesc = deferred(Column('CCStdDesc', String), group='ccstd_info')
CCStdName = deferred(Column('CCStdName', String), group='ccstd_info')
CCStdCluster = deferred(Column('CCStdCluster', String), group='ccstd_info')
@hybrid_property
def Cluster(self):
return self.CCStdCode[:1]
以下简单查询返回"Operator 'getitem' is not supported on this expression"
a=session.query(CCStandard.Cluster)
我确定这个专栏是一个字符串,所以不确定我为什么会这样做。如果我尝试使用+运算符,它确实有效,即:
@hybrid_property
def Cluster(self):
return self.CCStdCode + 'well this works'
底层数据库是SQLServer。这个列是一个nvarchar。
答案 0 :(得分:1)
SQLAlchemy不支持以这种方式查询子字符串。如果要查询具有子字符串的列,可以执行以下操作:
session.query(CCStandard).filter(CCStandard.CCStdCode.contains(sub_string))
如果要为子字符串创建自定义表达式,可以按照文档的说法进行操作。你必须使用expression
装饰器。这是一个最小的例子:
class CCStandard(Base):
"""Codes, grade, code description, and name"""
__tablename__ = "ccstandard"
CCStandardKey = Column(Integer, primary_key=True)
_CCStandardCode = Column(String)
@hybrid_property
def CCStandardCode(self):
return self._CCStandardCode
@CCStandardCode.setter
def CCStandardCode(self, code):
self._CCStandardCode = code
@hybrid_property
def Cluster(self):
return self._CCStandardCode[:1]
@Cluster.expression
def Cluster(cls):
# use the SQLite `substr` method to search for a substring
return func.substr(cls._CCStandardCode, 0, 2)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
>>> c = CCStandard(CCStandardKey=1, CCStandardCode="foo")
>>> session.add(c)
>>> session.commit()
>>> session.query(CCStandard).filter(CCStandard.Cluster == 'f').one()
<foo.CCStandard object at 0x1047305d0>