对于SQLAlchemy查询,如何将ilike搜索运算符与in_运算符组合?

时间:2014-08-18 15:29:37

标签: python postgresql sqlalchemy

我正在编写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_'

1 个答案:

答案 0 :(得分:8)

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

from sqlalchemy import func

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

否则,如果您想要多个'ilike'语句,

from sqlalchemy import or_

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

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

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