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

如何在SQLAlchemy与FastAPI中排除查询结果中的指定列

解决SQLAlchemy查询结果仅保留指定字段的问题

方法一:修改查询语句直接移除多余字段

既然不需要返回uid字段,直接从select()中去掉func.count(UserCountry.id).label("uid")即可——这个字段是你主动查询出来的,移除后结果自然只包含需要的字段。

修改后的查询代码:

statement = select(AuthUser.id, AuthUser.username).\
            join(CountryTool, CountryTool.id == UserCountry.country_tool_id).\
            join(Country, Country.id == CountryTool.country_id).\
            join(Tool, Tool.id == CountryTool.tool_id).\
            join(AuthUser, AuthUser.id == UserCountry.user_id).\
            where(CountryTool.id == country_tool_id).\
            group_by(AuthUser.id, AuthUser.username)

执行这个查询后,返回的结果会直接是只包含id和username的结构,无需额外处理就能得到你想要的JSON响应。

方法二:结果序列化时过滤字段

如果因为其他业务需求不能修改原始查询(比如其他场景需要用到uid字段),可以在将查询结果转为JSON的步骤中,过滤掉不需要的uid字段。

示例代码(以常见的SQLAlchemy结果处理为例):

# 执行查询并转为字典列表
raw_results = [dict(row) for row in db.session.execute(statement).all()]
# 仅保留需要的字段
filtered_results = [
    {"id": item["id"], "username": item["username"]}
    for item in raw_results
]
# 返回过滤后的JSON
return jsonify(filtered_results)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:40:27