如何通过字符串长度在`sqlalchemy`中过滤?

发布于 2021-01-29 14:58:42

如何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)
    ...
关注者
0
被浏览
122
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您需要使用funcSQL函数生成器来创建LENGTH()函数:

    from sqlalchemy.sql.expression import func
    
    sess.query(db.ArticlesTable).filter(or_(
        and_(func.length(db.ArticlesTable.shorttext) > 0),
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看