简体   繁体   English

sqlalchemy 过滤多列

[英]sqlalchemy filter multiple columns

How do I combine two columns and apply filter?如何组合两列并应用过滤器? For example, I want to search in both the "firstname" and "lastname" columns at the same time.例如,我想同时在“firstname”和“lastname”列中进行搜索。 Here is how I have been doing it if searching only one column:如果只搜索一列,我是这样做的:

query = meta.Session.query(User).filter(User.firstname.like(searchVar))

There are number of ways to do it:有多种方法可以做到:

Using filter() ( and operator)使用filter()运算符)

query = meta.Session.query(User).filter(
    User.firstname.like(search_var1),
    User.lastname.like(search_var2)
    )

Using filter_by() ( and operator)使用filter_by()运算符)

query = meta.Session.query(User).filter_by(
    firstname.like(search_var1),
    lastname.like(search_var2)
    )

Chaining filter() or filter_by() ( and operator)链接filter()filter_by()运算符)

query = meta.Session.query(User).\
    filter_by(firstname.like(search_var1)).\
    filter_by(lastname.like(search_var2))

Using or_() , and_() , and not()使用or_() and_()not()

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(
    and_(
        User.firstname.like(search_var1),
        User.lastname.like(search_var2)
    )
)

You can simply call filter multiple times:您可以简单地多次调用filter器:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or ).您可以使用 SQLAlchemy 的or_函数在多列中搜索(下划线是必要的,以将其与 Python 自己的or区分开来)。

Here's an example:下面是一个例子:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

A generic piece of code that will work for multiple columns.适用于多列的通用代码。 This can also be used if there is a need to conditionally implement search functionality in the application.如果需要在应用程序中有条件地实现搜索功能,也可以使用此方法。

search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()

Note: the %% are important to skip % formatting the query.注意: %%对于跳过 % 格式化查询很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM