简体   繁体   中英

SQLAlchemy filter for attributes containing all characters of substring, regardless of order

I am having issues trying to set up an SQLAlchemy query for my Flask app.

What I want to do is query the database for all usernames that contain the characters from an input in any order.

I know you can use User.query.filter(User.username.contains(input)) to check if a substring is present, but the substring must be in order for that.

For example, with that expression if my input was Marcus then it would work, filtering for my username MarcusWilliams . That is great, but I also want it to work if I have a username that contains all of the characters of the input regardless of their order.

For example, I would want all Marcus , sucraM , and MiWl to filter for my username, because in all cases the characters in the input are all present in the username.

I have tried a couple of things, such as checking if the set of characters from the input is a subset of the username set of characters, but the logic within the SQLAlchemy query is limited so that did not work.

Sorry if there is a simple solution that I am missing, any help is appreciated.

UPDATE:

With the help of the answer from @shipskin and with some edits I have made some progress.

By doing this:

User.query.filter(User.username.op('regexp')(".*".join(list(input))))

I am now able to match characters which have the all of the character in the username, but there is still a problem. The characters still have to be in the order they appear in the username, for example MWil would work, but WMill does not work, because the characters don't appear in that order in my username.

Take a look at https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.ColumnOperators.regexp_match

You could do something like Users.query.filter(User.username.op('regexp')('|'.join([c for c in input])) or generate a better regex.

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