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

Flask按ID返回单条Post数据报错:'Post'无'items'属性

问题分析与修复方案

核心问题原因

  • /explore路由中,Post.query.order_by(Post.timestamp.desc())如果配合了分页(比如调用过.paginate()),返回的是分页对象,这类对象自带items属性,对应分页后的帖子列表集合。
  • 而/explore/<int:id>路由里,Post.query.filter_by(id=id).first_or_404()直接返回的是单个Post实例对象,它本身就是单条帖子数据,不存在items属性,所以触发AttributeError。

修复步骤

  1. 修正item路由代码
    直接传递单个Post对象给模板,去掉多余的.items:

    @bp.route('/explore/<int:id>')
    def item(id):
        post = Post.query.filter_by(id=id).first_or_404()
        return render_template('item.html', title='Single Post', post=post)
    

    (把变量名从posts改成post,更贴合单条数据的语义,避免后续混淆)

  2. 调整item.html模板逻辑
    explore.html是遍历集合展示多条帖子,而item.html需要直接渲染单条帖子的属性,比如:

    <h2>{{ post.title }}</h2>
    <div class="post-content">{{ post.content }}</div>
    <p class="post-time">发布时间: {{ post.timestamp.strftime('%Y-%m-%d %H:%M') }}</p>
    

    不要用循环遍历post,因为它已经是单个对象,不是集合。

补充说明

你复制代码时忽略了两个路由的本质差异:一个返回多帖集合/分页对象,另一个返回单帖对象,所以不能直接复用.items的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:16:27