我目前正在从事一个博客项目,以进行学习,我正在尝试获取特定用户发布的帖子总数。在我的模型中,我将发表文章的用户设置为作者。
在“帖子详细信息”页面中,我想显示该特定作者发表的帖子总数,但是我正在获取查看该页面的已登录用户的数据。
这样做的原因是在获取上下文数据中使用了self,但是我不确定如何解决它,因此我需要一些有关如何在代码中修改此错误的解释。
这是邮政模型:
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
content = RichTextUploadingField(null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
这是views.py:
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html"
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
post = get_object_or_404(Post, slug=self.kwargs['slug'])
num_post = Post.objects.filter(author=self.request.user).count()#<--- No. of Posts made by an author
context["num_post"] = num_post #<--- No. of Posts made by a user
return context
我的问题:如何显示帖子详细信息作者的数据而不是已登录的用户
谢谢
代替
num_post = Post.objects.filter(author=self.request.user).count()
和:
num_post = Post.objects.filter(author=post.author).count()