gpt4 book ai didi

python - 对于 SQLAlchemy 查询,如何将 ilike 搜索运算符与 in_ 运算符结合使用?

转载 作者:太空宇宙 更新时间:2023-11-03 13:00:05 25 4
gpt4 key购买 nike

我正在编写 SQLAlchemy 代码,它接受搜索栏的输入并对我的 PostgreSQL 数据库运行查询。为了允许拼写错误和名称片段,我使用这段代码来解决问题:

q = session.query(Detail).filter((Detail.sellers.ilike("%%%s%%" % (name_input)))).all()

现在我正在尝试做同样的事情,但要检查具有多个输入值的列表 names。我是这样完成的:

q = session.query(Detail).filter((Detail.sellers.in_(names))

然而,这需要完全匹配。我想结合使用 ilike 运算符和 in_ 运算符。这可能吗?我试过:

q = session.query(Detail).filter((Detail.sellers.ilike.in_(names))

这给出了以下回溯和错误:

File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Tom/projects/land-records/repo/scripts/app.py", line 162, in search
return query_db(names)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask_cache/__init__.py", line 537, in decorated_function
rv = f(*args, **kwargs)
File "/Users/Tom/projects/land-records/repo/scripts/app.py", line 106, in query_db
q = session.query(Detail).filter((Detail.sellers.ilike.in_(names))).all()

AttributeError: 'function' object has no attribute 'in_'

最佳答案

如果只是不区分大小写的 'in_' 语句:

from sqlalchemy import func

q = session.query(Detail).filter(
func.lower(Detail.sellers).in_(map(str.lower, names))
)

否则,如果您想要多个“喜欢”语句,

from sqlalchemy import or_

conditions = []
for name in names:
conditions.append(Detail.sellers.ilike('%{}%'.format(name)))

q = session.query(Detail).filter(
or_(*conditions)
)

我还没有测试它,如果它不起作用,我可以编辑它。

关于python - 对于 SQLAlchemy 查询,如何将 ilike 搜索运算符与 in_ 运算符结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25366895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com