Home > Software engineering >  Display the number of comments of each post related to the same post in django
Display the number of comments of each post related to the same post in django

Time:09-13

Hello friends I am building a blog and I have encountered a problem. My problem is that when I want to display the number of comments for each post, on the main page of the blog number of comments displays all posts that have comments, but the number of comments for each post is the same. In the event that post 2 has 3 comments and the other has 1 comment.

You can see in this picture. Image

This is my models.py

class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
email = models.EmailField()
comment = models.CharField(max_length=500)
active = models.BooleanField(default=False)
created_date = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return "{} by {}".format(self.comment, self.name)

This is my views.py

def post_list(request):
posts = models.Post.objects.filter(status='published')
paginator = Paginator(posts, 4)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
comment_count = models.Comment.objects.filter(active=True).count()
context = {
    'page_obj': page_obj,
    'comment_count': comment_count,
}
# print(posts)
return render(request, "post_list.html", context=context)

And this too post_list.html

        <article >
        <hr >

        <a href="{{ post.get_absolute_url }}"
           >
            <div >
                <img src="/{{ post.image }}/" alt="Image" >
            </div>

            <h2 >{{ post.title }}</h2>
        </a>

        <p >
            {{ post.body|slice:254 }}
        </p>

        <div >
            <span >Travel . Events</span>
            <span >{{ post.created_date.year }}/{{ post.created_date.month }}/{{ post.created_date.day }}</span>
        </div>

        <hr>

        <div >
                <span>
                    {% for comment in post.active_comment|slice:"1" %}
                        {{ comment_count }}<span> Comment</span>
                    {% endfor %}
                </span>
            <span>{{ post.author|capfirst }}</span>
        </div>
    </article>

please guide me.

CodePudding user response:

You can .annotate(…) [Django-doc] with:

from django.db.models import Count, Q

# …

posts = Post.objects.annotate(number_of_comments=Count('comment_set', filter=Q(comment_set__active=True)))

The Post objects that arise from this QuerySet will have an extra attribute .number_of_comments.

CodePudding user response:

based on @willem post you need to edit your template accordingly too:

posts = Post.objects.annotate(number_of_comments=Count('comment_set', filter=Q(comment_set__active=True)))

and in the template

<div >
   <span>{{post.number_of_comments}}</span>
   <span>{{ post.author|capfirst }}</span>
</div>
  • Related