Look at this answer: Case Insensitive Flask-SQLAlchemy Query
Why is it better to use SQLAlchemy's func.lower(mystring)
instead of python's native mystring.lower()
?
Look at this answer: Case Insensitive Flask-SQLAlchemy Query
Why is it better to use SQLAlchemy's func.lower(mystring)
instead of python's native mystring.lower()
?
The context is important.
user = models.User.query.filter(func.lower(User.username) == func.lower("GaNyE")).first()
Here, there is no string with a lower
method to call; you are composing a SQL command to execute in the database. func.lower
doesn't return a lowercase string; it returns an object that represents SQL code that can be used to produce a lowercase string.
As mgilson points out, there's no need to use func.lower
on actual Python values; they are constant for each row the filter will be applied against, but I'm not sure SQLAlchemy is able to detect and optimize such situations. Either of the following
user = models.User.query.filter(func.lower(User.username) == "ganye").first()
user = models.User.query.filter(func.lower(User.username) == "GaNyE".lower()).first()
would produce SQL code like lower(username) = :lower_1
instead of lower(username) = lower(:lower_1)
, which can make the SQL query more efficient by eliminating a call to lower
for each line.