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

Count the number of Likes received by a user for all his posts

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

I am trying to get the total number of likes given to a user which is in my case the author of the post.

I have commented my trial as it didn't work.

Here is the 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)

Here is the views.py that I have tried

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})

Here is the template:

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

Update: In order to try to fix this I have added:

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


My question is: How to get the total number of likes given for all the posts given to a particular author

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

You can do the following to get the post.author's all likes.

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