头图

When using Python for web development, SQLAlchemy is usually used in the OR Mapping part, which is a relatively heavyweight database encapsulation layer that provides rich calling interfaces.

Implementing a query with SQLAlchemy is fairly straightforward, such as the following SQL:

select * from table_a where col1=3 and col2='abc'

Written in code is:

TableA.query.filter(TableA.col1==3).filter(TableA.col2=='abc')

But sometimes, we will find that there are often two or more queries in the code, and their conditions are exactly the same, only there is a difference after the select, for example, I want to take a total number:

select count(*) from table_a where col1=3 and col2='abc'
db.session.query(func.count('*').filter(TableA.col1==3).filter(TableA.col2=='abc')

This is very awkward. The same code is written repeatedly. If this condition is complicated and requires various logical judgments to splicing, it will be even more uncomfortable: each splicing statement must be copied once, and the bad smell of the code will overflow the screen~~ ~

Is there a way to make them share the same filter? There are some, you can use list nested expressions, save the filter first, and finally pass it to the query object together:

all_filters = [
    TableA.col1==3,
    TableA.col2=='abc'
]

records = TableA.query.filter(*all_filters).all()

count = db.session.query(
    func.count('*')
).filter(
    *all_filters
).first()

There are not many articles describing this problem on the Internet. After google for a long time, I found an answer: Apply condition based multiple filters in SQLAlchemy query

The problem with is that it still has an error. It wrote *all_filters as **all_filters , which made me almost give up.


songofhawk
303 声望24 粉丝