如何从 sql 炼金术过滤器中的字符串变量动态给出列名



我想在sql炼金术过滤器中创建查询,但是列在变量中是(动态的)/在变量中指定。

原始查询:

db_session.query(Notice).filter(Notice.subject.like("%" +query+ "%"))

我想像这样做查询:

col_name='subject'
db_session.query(Notice).filter(Notice.col_name.like("%" +query+ "%"))
col_name='status'
status=0
db_session.query(Notice).filter(Notice.col_name != 1)

只需使用 getattr 标准 python 库函数按名称获取属性:

col_name = 'subject'
db_session.query(Notice).filter(getattr(Notice, col_name).like("%" + query + "%"))

在较新的sqlalchemy版本中,应该这样做:

Notice.__table__.c[col_name]

所以:

(db_session
    .query(Notice)
    .filter(Notice.__table__.c[col_name].like("%" + query + "%")
)

我尝试了@vans解决方案,但没有奏效。我总是收到一个 AttributeError 抱怨我的表没有该列。对我有用的是table.columns

getattr(Notice.columns,col_name)

接受的答案有一个解决方案,但已经过时了。

SQLAlchemy 1.3建议将所有文本过滤器放在text()中,并连接and。文档

示例:session.query(User).filter(text("id<224")).order_by(text("id")).all()

来自不同查询的文档的另一个示例

>>> s = select([
...        text("users.fullname || ', ' || addresses.email_address AS title")
...     ]).
...         where(
...             and_(
...                 text("users.id = addresses.user_id"),
...                 text("users.name BETWEEN 'm' AND 'z'"),
...                 text(
...                     "(addresses.email_address LIKE :x "
...                     "OR addresses.email_address LIKE :y)")
...             )
...         ).select_from(text('users, addresses'))

最新更新