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

Django类视图中如何展示关联Post模型外键的对应评论内容

解决方案

你当前代码的核心问题是直接调用了Post模型类的反向关联方法,没有绑定到当前详情页对应的具体Post实例,所以无法拿到指定帖子的关联评论。

修正后的视图代码

class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # self.object就是当前详情页加载的单个Post实例,这里增加排序让最新评论靠前
        context['comment_list'] = self.object.comment_set.order_by('-create_date').all()
        return context

模板调用示例

你可以在对应的post_detail.html模板中直接遍历comment_list变量渲染评论:

<!-- 评论区示例 -->
<div class="comment-section">
  <h3>全部评论</h3>
  {% for comment in comment_list %}
  <div class="comment-item">
    <p>{{ comment.owner.username }} 发布于 {{ comment.create_date|date:"Y-m-d H:i" }}</p>
    <p>{{ comment.text }}</p>
  </div>
  {% empty %}
  <p>暂无评论,快来抢沙发吧</p>
  {% endfor %}
</div>

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

相关产品推荐
方舟 Agent Plan

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

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