问题:不区分大小写的Flask-SQLAlchemy查询
我正在使用Flask-SQLAlchemy从用户数据库中查询;但是,虽然
user = models.User.query.filter_by(username="ganye").first()
将返回
<User u'ganye'>
在做
user = models.User.query.filter_by(username="GANYE").first()
退货
None
我想知道是否有一种以不区分大小写的方式查询数据库的方法,以便第二个示例仍会返回
<User u'ganye'>
I’m using Flask-SQLAlchemy to query from a database of users; however, while
user = models.User.query.filter_by(username="ganye").first()
will return
<User u'ganye'>
doing
user = models.User.query.filter_by(username="GANYE").first()
returns
None
I’m wondering if there’s a way to query the database in a case insensitive way, so that the second example will still return
<User u'ganye'>
回答 0
您可以使用过滤器中的lower
或upper
功能来实现:
from sqlalchemy import func
user = models.User.query.filter(func.lower(User.username) == func.lower("GaNyE")).first()
另一种选择是使用ilike
而不是进行搜索like
:
.query.filter(Model.column.ilike("ganye"))
You can do it by using either the lower
or upper
functions in your filter:
from sqlalchemy import func
user = models.User.query.filter(func.lower(User.username) == func.lower("GaNyE")).first()
Another option is to do searching using ilike
instead of like
:
.query.filter(Model.column.ilike("ganye"))
回答 1
如果仅指定所需的列,则可以改善@plaes的答案,这将使查询更短:
user = models.User.query.with_entities(models.User.username).\
filter(models.User.username.ilike("%ganye%")).all()
上面的例子中的情况下是非常有用的一个功能需要使用瓶的jsonify对AJAX的目的,然后在你的JavaScript访问它使用data.result:
from flask import jsonify
jsonify(result=user)
Improving on @plaes’s answer, this one will make the query shorter if you specify just the column(s) you need:
user = models.User.query.with_entities(models.User.username).\
filter(models.User.username.ilike("%ganye%")).all()
The above example is very useful in case one needs to use Flask’s jsonify for AJAX purposes and then in your javascript access it using data.result:
from flask import jsonify
jsonify(result=user)
回答 2
你可以做
user = db.session.query(User).filter_by(func.lower(User.username)==func.lower("GANYE")).first()
或者您可以使用ilike函数
user = db.session.query(User).filter_by(User.username.ilike("%ganye%")).first()
you can do
user = db.session.query(User).filter_by(func.lower(User.username)==func.lower("GANYE")).first()
Or you can use ilike function
user = db.session.query(User).filter_by(User.username.ilike("%ganye%")).first()