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

SQLAlchemy如何从已查询的Program对象中筛选2021年的关联Program_Session记录

SQLAlchemy 按条件查询关联模型的实现方法

完全可以实现,以下是几种不同场景下的常用方案:


  • 方案1:基于已获取的Program实例做内存过滤
    适合已经拿到Program实例、且关联的Program_Session数据量不大的场景,直接对关联属性做过滤即可:
# 直接遍历关联的session列表,筛选符合年份要求的记录
sessions_2021 = [session for session in program.program_sessions if session.session_year == 2021]
  • 方案2:数据库层面直接条件查询(性能更优)
    如果关联的Session数据量较大,不想把所有关联记录都查询到内存再过滤,可以直接针对Program_Session构造查询,在数据库层面完成过滤:
sessions_2021 = Program_Session.query.filter(
    Program_Session.program_id == program.id,
    Program_Session.session_year == 2021
).all()

也可以用SQLAlchemy提供的with_parent方法简化关联条件的编写,无需手动指定外键匹配:

from sqlalchemy.orm import with_parent

sessions_2021 = Program_Session.query.options(
    with_parent(program)
).filter(Program_Session.session_year == 2021).all()
  • 方案3:查询Program时同步预加载过滤后的Session
    如果需要在查询Program实例的同时就加载好2021年的关联Session,避免后续二次查询,可以用带过滤的预加载方案:
from sqlalchemy.orm import contains_eager

program = Programs.query.join(
    Programs.program_sessions
).filter(
    Program_Session.session_year == 2021
).options(
    contains_eager(Programs.program_sessions)
).first()

# 此时直接访问program.program_sessions就只有2021年的记录
print(program.program_sessions)

内容的提问来源于stack exchange,提问作者The Peace of Programming

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 09:36:10