For SQLAlchemy query, how to combine the ilike search operator with the in_ operator?
I am writing SQLAlchemy code that takes a search string input and runs a query against my PostgreSQL database. To allow for typos and snippet names, I had this code that did the trick:
q = session.query(Detail).filter((Detail.sellers.ilike("%%%s%%" % (name_input)))).all()
Now I am trying to do the same, but validate a list names
that has multiple input values. I did it like this:
q = session.query(Detail).filter((Detail.sellers.in_(names))
This requires exact matches. I would like to combine operator ilike
and operator in_
. Is it possible? I tried:
q = session.query(Detail).filter((Detail.sellers.ilike.in_(names))
This gives the following traceback and error:
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_'
+3
source to share
1 answer
If it is about the case insensitive 'in_' operator:
from sqlalchemy import func
q = session.query(Detail).filter(
func.lower(Detail.sellers).in_(map(str.lower, names))
)
Otherwise, if you want to have multiple ilike operators,
from sqlalchemy import or_
conditions = []
for name in names:
conditions.append(Detail.sellers.ilike('%{}%'.format(name)))
q = session.query(Detail).filter(
or_(*conditions)
)
I haven't tested it, if it doesn't work I can edit it.
+7
source to share