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

SQLAlchemy查询指定学生参与的志愿活动报list无events_id属性如何解决

错误原因

volunteer2122.query.filter_by(student_id=student.id).all() 返回的是参与记录对象的列表,列表本身没有 events_id 属性,只有列表内的单个参与记录对象才有该属性,直接调用列表的 events_id 就会触发你遇到的报错。

解决方案

这里提供两种可行方案,前端代码无需修改即可直接兼容:

方案1(推荐,利用ORM关联关系)

你已经在模型中定义好了完整的关联关系,直接通过关联查询即可快速拿到数据,代码更简洁:

@app.route("/v_student_detail/<id>")
def v_student_detail(id):
    student = student2122.query.filter_by(id=id).first()
    # 遍历学生关联的参与记录,提取对应活动对象
    events = [record.event for record in student.events]
    return render_template('/sv_record/voluntary_record/v_student_detail.html', student=student, events=events)

方案2(手动查询修正)

如果需要手动写查询逻辑,先提取所有活动ID再批量查询即可:

@app.route("/v_student_detail/<id>")
def v_student_detail(id):
    student = student2122.query.filter_by(id=id).first()
    done_activities = volunteer2122.query.filter_by(student_id=student.id).all()
    # 提取所有参与记录对应的活动ID列表
    event_id_list = [item.events_id for item in done_activities]
    # 用in条件批量查询所有符合的活动
    events = voluntary2122.query.filter(voluntary2122.id.in_(event_id_list)).all()
    return render_template('/sv_record/voluntary_record/v_student_detail.html', student=student, events=events)

内容的提问来源于stack exchange,提问作者wing yan chan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:15:05