Python 不区分大小写的 Flask-SQLAlchemy 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16573095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:02:47  来源:igfitidea点击:

Case Insensitive Flask-SQLAlchemy Query

pythonflaskflask-sqlalchemy

提问by Ganye

I'm using Flask-SQLAlchemy to query from a database of users; however, while

我正在使用 Flask-SQLAlchemy 从用户数据库中查询;然而,虽然

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'>

采纳答案by plaes

You can do it by using either the loweror upperfunctions in your filter:

您可以通过在过滤器中使用lowerupper函数来实现:

from sqlalchemy import func
user = models.User.query.filter(func.lower(User.username) == func.lower("GaNyE")).first()

Another option is to do searching using ilikeinstead of like:

另一种选择是使用ilike而不是进行搜索like

.query.filter(Model.column.ilike("ganye"))

回答by iChux

Improving on @plaes's answer, this one will make the query shorter if you specify just the column(s) you need:

改进@plaes 的答案,如果您只指定所需的列,这个答案将使查询更短:

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:

如果需要将 Flask 的 jsonify 用于 AJAX 目的,然后在您的 javascript 中使用data.result访问它,则上面的示例非常有用:

from flask import jsonify
jsonify(result=user)

回答by Mohammad Aarif

you can do

你可以做

user = db.session.query(User).filter_by(func.lower(User.username)==func.lower("GANYE")).first()

Or you can use ilike function

或者你可以使用 ilike 功能

 user = db.session.query(User).filter_by(User.username.ilike("%ganye%")).first()