Home > Enterprise >  Number of times Tags used in post which were commented by user
Number of times Tags used in post which were commented by user

Time:09-21

I am building a simple Blog App and I am trying to implement a feature.

In which, If a user commented on a post with post tags - tag1, tag2. And I will retrieve the Tags of which user commented on post And i am trying to count Number of times a user commented on a post with same tag

Like I am trying to show :-

Tag Name Number of times used
tag1 16 Times
tag2 10 Times
tag3 8 Times

This table is showing :- User commented on a post with the tag which was used in previous post.

For Example :-

A new user named "user_1" commented on a Post with tags tag5, tag6, tag8 then A query will show that user_1 has commented on post tags 1 times in tag5 , 1 time in tag6 and 1 time in tag8. And I will do the rest later.

models.py

class BlogPost(models.Model):
    user = models.ForeinKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    tags = TaggableManager()

class Comment(models.Model):
    comment_by = models.ForeignKey(User, on_delete=models.CASCADE)
    on_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)

views.py

def examplePage(request):
    query = Tag.objects.filter(blogpost__user=request.user)

    context = {'query': query}
    return render(request, 'examplePage.html', context)

This view is showing tags which are used in post which were commented by request.user like :-

tag1

tag2

tag2

But I have no idea, How can i annotate so it can show number of used tags which were on post commented by request.user like above table.

Any help would be much Appreciated. Thank You.

Note :- I am using Django-Taggit for Tags (TaggableManager() in BlogPost Model)

CodePudding user response:

I think using blogpost__user would cause the tag to be filtered by (I assume) the author of the BlogPost instead of the commenter, so I think you would want to use blogpost__comment__comment_by?

With that you can annotate on the count of tags like this:

Tag.objects.filter(
    blogpost__comment__comment_by=request.user
).values(
    'name'
).annotate(
    times_used=Count('name')
)
  • Related