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

在Django模板的对象列表循环中获取对象索引

在Django模板中遍历评论列表时获取当前评论的索引

核心解决方法

Django模板的for循环内置了获取索引的变量,直接使用即可:

  • {{ forloop.counter }}:返回从1开始的索引值
  • {{ forloop.counter0 }}:返回从0开始的索引值

你可以在循环内部直接调用这些变量,拿到当前评论的对应索引。

修改后的模板代码

<!-- comment list section -->
<div class="card shadow my-3 p-5">
    <h3>Comments:</h3>
<!-- checking if any comment exist on this post -->
    {% if comments.count < 1 %}
        No comments. write the first one!
    {% else %}
        <!-- iterating on comments and showing them -->
        {% for comment in comments %}
            <div id="comment-div">
                <span>序号:{{ forloop.counter }}</span>
                <span id="Comment-name">by: {{ comment.name }}</span>
                <span id="Comment-date">{{ comment.datetime_created|date:'M d Y' }}</span>
                <p id="Comment-body">{{ comment.body }}</p>
            </div>
        {% endfor %}
    {% endif %}
</div>

视图代码优化提示

当前视图中获取评论的逻辑会返回所有已审核通过的评论,而非当前文章的专属评论。请修改get_context_data方法,过滤出当前文章的关联评论:

class PostDetailView(FormMixin, generic.DetailView):
    model = Post
    template_name = 'blog/post_detail.html'
    context_object_name = 'post'
    form_class = CreateComment

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 仅获取当前文章下已通过审核的评论
        context['comments'] = self.object.comments.filter(accepted=True)
        return context

这里利用了Comment模型中post外键设置的related_name='comments',self.object是DetailView自动实例化的当前Post对象,通过self.object.comments可直接获取该文章的所有关联评论,再叠加审核状态过滤即可。

模型代码无需调整

你的Comment模型定义规范,related_name='comments'的设置确保了Post与Comment之间的关联查询逻辑正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:48:18