Case Insensitive Flask-SQLAlchemy Query

后端 未结 3 1437
广开言路
广开言路 2020-11-28 06:25

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

user = models.User.query.filter_by(username=\"ganye\").first()
<
相关标签:
3条回答
  • 2020-11-28 06:55

    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)
    
    0 讨论(0)
  • 2020-11-28 07:04

    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()
    
    0 讨论(0)
  • 2020-11-28 07:07

    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"))
    
    0 讨论(0)
提交回复
热议问题