如何按字符串长度过滤`sqlalchemy`? [英] How to filter in `sqlalchemy` by string length?

查看:22
本文介绍了如何按字符串长度过滤`sqlalchemy`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to filter in sqlalchemy by string length?

此代码片段:

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)
    ...

推荐答案

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

You need to use the func SQL function generator to create a LENGTH() function:

from sqlalchemy.sql.expression import func

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

这篇关于如何按字符串长度过滤`sqlalchemy`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆