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

Viewed 43

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.

1 Answers
Related