如何按字符串长度过滤`sqlalchemy`?

时间:2013-04-01 12:01:45

标签: python sqlalchemy

如何按字符串长度过滤sqlalchemy

此代码段:

sess.query(db.ArticlesTable).filter(or_(
    and_(db.ArticlesTable.shorttext.length > 0),
         ...

给了我以下错误:

File "./aggregate_news.py", line 69, in is_acceptable
    db.ArticlesTable.shorttext.length > 0),
  File ".../sqlalchemy/orm/attributes.py", line 211, in __getattr__
    key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' 
    object associated with ArticlesTable.shorttext has an attribute 'length'

ArticlesTable的位置:

class ArticlesTable(Base):
    __tablename__ = TABLE_ARTICLES
    id = Column(Integer, primary_key=True)
    shorttext = Column(String)
    ...

1 个答案:

答案 0 :(得分:17)

您需要使用func SQL function generator创建LENGTH()功能:

from sqlalchemy.sql.expression import func

sess.query(db.ArticlesTable).filter(or_(
    and_(func.length(db.ArticlesTable.shorttext) > 0),