You need to enable JavaScript to run this app. 使用Jinja与PyMongo渲染好友请求时循环重复输出问题
优惠活动
大模型
产品
解决方案
定价
更多

使用Jinja与PyMongo渲染好友请求时循环重复输出问题

问题根因

页面重复输出3次相同内容,是两处逻辑错误叠加导致的:

  • 路由端误用find_one():该方法只会返回匹配到的第一条好友请求文档,而非所有发给当前用户的请求集合
  • 模板循环逻辑错误:
    1. 当传入单个字典类型的find_request对象时,Jinja的for循环遍历字典会默认迭代字典的所有键(你当前测试的字典共3个键:_id、friend_request_from、friend_request_to),因此循环会执行3次
    2. 循环体中没有引用每次遍历得到的临时变量,始终读取外层传入的单个find_request对象的固定friend_request_from字段,因此循环执行多少次就重复输出多少次相同的发送方内容,最终呈现出连续3次相同输出的效果

修改方案

1. 调整Flask路由代码

将原本单条查询的find_one()替换为全量查询的find(),把匹配到的所有好友请求以列表形式传给模板,同时优化登录状态判断避免KeyError:

@app.route("/friend_requests", methods=["GET", "POST"])        
def friend_requests():
    user = session.get("user")
    # 无有效登录用户时传空列表给模板,避免查询异常
    if not user:
        return render_template("friend_requests.html", find_requests=[])
    # 查询所有发给当前用户的好友请求,转成列表方便模板迭代
    find_requests = list(mongo.db.friend_requests.find({"friend_request_to": user}))
    return render_template("friend_requests.html", find_requests=find_requests)

2. 修正模板的循环逻辑

替换原本错误的循环写法,正确遍历每个好友请求对象,同时补充空状态提示:

{% if find_requests %}
    {% for request in find_requests %}
        <span>from {{ request.friend_request_from }}</span>
    {% endfor %}
{% else %}
    <span>暂无收到的好友请求</span>
{% endif %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 16:45:05