0

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.

1 Answer 1

2

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
)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.