简体   繁体   中英

Query processing in SQL Alchemy - Python

I need the dynamic Query processing with the SQLAlchemy.

Consider there is the table which is having three field name,age,city.

From the table I need to fetch the city like city name having (s,r,t) characters.

For that SQLAlchemy Query which I framed is as follows:

query = query.filter(or_(model.city.like('%s%'),model.city.like('%r%'),model.city.like('%t%')))

It is working as I expected.

But now my issue is regarding processing of the values during my code execution.

Because in my case those characters needs to be taken from the list in python.

Consider python list:

['s','m','n']

So here now Querying is needs to be done for those values in list dynamically.

I can't be sure regarding the number of entries in list too, So that it should be working dynamically.

Main goal here here is doing "like" and "or" in SQLAlchemy dynamically.

You can map the list characters through the like() method and splat the result into _or() . Something along the lines of:

chars = ['s','m','n']

query = query.filter(or_(*map(
                              lambda x: model.city.like('%{}%'.format(x)),
                              chars
)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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