You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask-SQLAlchemy:如何匹配多列中包含指定值的记录?

问题原因与解决方法

你的代码没生效是因为SQLAlchemy的filter方法中,多个参数默认是**AND(且)逻辑,会要求username和tag同时包含user_like才会返回结果,但你需要的是OR(或)**逻辑——只要其中一个字段包含目标值就匹配。

解决方法是用SQLAlchemy提供的or_函数来组合两个条件:

  1. 先导入or_:
from sqlalchemy import or_
  1. 修改查询代码:
matched_users = User.query.filter(
    or_(
        User.username.like(f'%{user_like}%'),
        User.tag.like(f'%{user_like}%')
    )
).all()

这样就能正确匹配所有username或tag包含user_like的用户了。

内容的提问来源于stack exchange,提问作者TheGabDooSan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:54:19