Warm tip: This article is reproduced from serverfault.com, please click

python-计算用户收到的所有帖子的点赞次数

(python - Count the number of Likes received by a user for all his posts)

发布于 2020-11-27 03:03:00

我正在尝试获得给用户的喜欢总数,在我看来author是帖子的总数

我评论了我的审判,因为它没有用。

这是models.py

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
    likes = models.ManyToManyField(User, related_name='liked', blank=True)
class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

这是我尝试过的views.py

class PostDetailView(DetailView):
    model = Post
    template_name = "blog/post_detail.html" 

    def total_likes_received(request):
        #total_likes_received = Post.likes.filter(author=request.user).count() 
        return render(request, 'blog/post_detail.html', {'total_likes_received': total_likes_received})

这是模板:

<small class="ml-5 mr-2" >Total {{ total_likes_received }} </small>

更新: 为了尝试解决此问题,我添加了:

class PostDetailView(DetailView):
    model = Post
    template_name = "blog/post_detail.html"  # <app>/<model>_<viewtype>.html

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        total_likes_received = Post.likes.filter(author=self.request.user).count()
What should I add here to show the total likes of all posts of an author not the logged in user
        context['total_likes_received'] = total_likes_received


我的问题是: 如何获得给特定作者的所有帖子的喜欢总数

Questioner
A_K
Viewed
0
ha-neul 2020-11-28 12:15:24

你可以按照以下步骤获得帖子。作者的所有赞。

post = get_object_or_404(Post, pk=self.kwargs['pk']) 
total_likes_received = Like.objects.filter(post__author=post.author).count()