search

Home  >  Q&A  >  body text

python - SQLAlchemy中模糊查询,如何like多个关键字

比如需要找出u_name中既有“三”又有“猫”的记录:
SQL原生语句如下:

SELECT * FROM [user] WHERE u_name LIKE '%三%' AND u_name LIKE '%猫%'

请问这个如何在 SQLAlchemy 中实现呢

大家讲道理大家讲道理2814 days ago1180

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:55:02

    from sqlalchemy import and_
    
    
    words = ['%三%', '%猫%']
    rule = and_(*[table.u_name.like(w) for w in words])
    table.query.filter(rule)

    reply
    0
  • PHPz

    PHPz2017-04-17 17:55:02

    DBSession().query(user).filter(user.u_name.like('%三%')).filter(user.u_name.like('%猫%'))
    
    

    Or you can use and_()

    DBSession().query(user).filter(and_(user.u_name.like('%三%'), user.u_name.like('%猫%')))
    

    reply
    0
  • Cancelreply