如何通过get_context_data在ListView中的每个博客文章中获取评论计数?通过self.id/self.


from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from journal.models import Post, Corrections, Comments
class PostListView(ListView):
    model = Post
    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        context['comment_count'] = Comments.objects.filter(post_id=self.id).count()
        return context

这是代码的有问题的行:

context['comment_count'] = Comments.objects.filter(post_id=self.id).count()

如果我用一个数字手动替换self.id,则它将正确获取帖子的评论计数。

这使我提出了我的问题:

如果我在listView中,我该如何获得post.id?

编辑:

from django.urls import path
from journal.views import PostListView, PostDetailView
urlpatterns = [
    path('', PostListView.as_view(), name='post-list'),
    path('<int:pk>/', PostDetailView.as_view(), name='post-detail'),
]

您应该已经发布了模型。假设您有一个来自评论的外国键,并且尚未指定related_name,则可以在模板中执行此操作:

 {% for post in object_list %}
    {{ post.title }} # etc
    {{ post.comment_set.count }}
 {% endfor %}

如果您确实设置了一个相关的_name,请使用它代替comment_set

最新更新