Search code examples
pythondjangowebblogs

Getting the number of comments from a specific post in django


I have a little problem with a query. I work on a blog website with django. For posts I have the first page where i display all the posts as a list, with their details (title, date posted etc.) and I want to display the number of comments for each post along with title, date posted and tags. I'm not sure how to make that, I need to implement something on the model classes or in view function that renders the page ? Here are the model classes.

class Post(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=500)
    content = models.TextField()
    tags = models.CharField(max_length=100)
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title


class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    comment_text = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f'{self.user.username} Comment ' + str(self.id)

and the view function

def blog(request):

    context = {
        'posts': Post.objects.all(),
        'title': 'Blog',
        'banner_page_title': 'Blog',
        'page_location': 'Home / Blog'
    }
    return render(request, 'blog/blog.html', context)

Solution

  • Method 1:

    You can use this in your template.

    {% for post in posts %}
        {{ post.comment_set.count }}
    {% endfor %}
    

    Method 2:

    You can implement a model method like this:

    class Post(models.Model):
        ....
        def __str__(self):
            return self.title
    
        @property
        def comment_count(self):
            return self.comment_set.count()
    

    And you can call the model method in your template like this:

    {% for post in posts %}
        {{ post.comment_count }}
    {% endfor %}