Fix Python – Case Insensitive Flask-SQLAlchemy Query

Question

Asked By – 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'>

Now we will see solution for issue: Case Insensitive Flask-SQLAlchemy Query


Answer

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"))

This question is answered By – plaes

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0