AttributeError: 'TextualSelect' object has no attribute 'filter'

AttributeError: 'TextualSelect' object has no attribute 'filter'

当运行下面的查询时,在sqlalchemy 1.4.18中,我得到以下错误: AttributeError: 'TextualSelect' 对象没有属性 'filter'.

如何在 TextualSelect 对象上进一步使用 sqlalchemy?,而不必在原始文本查询中包含所有可能的过滤等。

这只是一个最小的例子:

query = text("""SELECT somecolumn FROM sometable```).columns(somecolumn=String)
subquery = text("""
 SELECT somecolumn FROM someothertable
 WHERE someothercolumn is not null
""").columns(somecolumn=String)
query = query.filter(query, query.c.somecolumn.in_(subquery))

.text() 不生成可选对象,因此它没有 .filter().where() 方法。

import sqlalchemy as sa

tbl = sa.Table(
    "tbl",
    sa.MetaData(),
    sa.Column("id", sa.Integer, primary_key=True, autoincrement=False),
)

txt = sa.text("SELECT id FROM tbl")
print(type(txt))  # <class 'sqlalchemy.sql.elements.TextClause'>

qry = txt.where(tbl.c.id > 1)
# AttributeError: 'TextClause' object has no attribute 'where'

但是,如果您将 .text() 对象传递给 .select(),那么您可以进一步调整该可选对象:

qry = sa.select(txt)
print(type(qry))  # <class 'sqlalchemy.sql.selectable.Select'>

qry = qry.where(tbl.c.id > 1)
print(qry)
"""
SELECT SELECT id FROM tbl 
FROM tbl 
WHERE tbl.id > :id_1
"""

(顺便说一句,SQLAlchemy 1.4+ .where() 优于 .filter()。)