简体   繁体   English

SQLAlchemy 过滤包含 substring 的所有字符的属性,无论顺序如何

[英]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.我在尝试为我的 Flask 应用程序设置 SQLAlchemy 查询时遇到问题。

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.我知道您可以使用User.query.filter(User.username.contains(input))来检查 substring 是否存在,但 substring 必须是为了这个。

For example, with that expression if my input was Marcus then it would work, filtering for my username MarcusWilliams .例如,使用该表达式,如果我的输入是Marcus ,那么它将起作用,过滤我的用户名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.例如,我希望所有MarcussucraMMiWl都过滤我的用户名,因为在所有情况下,输入中的字符都存在于用户名中。

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.我尝试了几件事,例如检查输入中的字符集是否是用户名字符集的子集,但 SQLAlchemy 查询中的逻辑受到限制,因此无法正常工作。

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.在@shipskin 的回答和一些编辑的帮助下,我取得了一些进展。

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.字符仍然必须按照它们在用户名中出现的顺序排列,例如MWil可以工作,但WMill不起作用,因为这些字符在我的用户名中没有按该顺序出现。

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

You could do something like Users.query.filter(User.username.op('regexp')('|'.join([c for c in input])) or generate a better regex.您可以执行类似Users.query.filter(User.username.op('regexp')('|'.join([c for c in input]))的操作或生成更好的正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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