Skip to main content
 首页 » 编程设计

python之使用 .contains() 的 SQLAlchemy 搜索过于敏感

2025年05月04日1598°冷暖

我有一个 Flask 应用程序,它有一个搜索栏,用户可以在其中搜索数据库中的用户。这是代码:

users = [] 
for keyword in query.split(): 
  result = db.session.query(Users).filter(User.name.contains(keyword)).all() 
  for user in result: 
    users.append(user.name) 

使用上面的示例,如果我要搜索“a”,那么名称中包含字母“a”的每个用户都会出现。我如何搜索用户表,而不是按字母搜索,而是按单词搜索?谢谢。

请您参考如下方法:

您可以在 SQLAlchemy 中使用正则表达式:

result = db.session.query(Users).filter(User.name.op('regexp')(r'\b{}\b'.format(keyword))).all() 

\b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. For example, r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.

https://docs.python.org/2/library/re.html