Reputation: 3100
I have a simple blog created in Django with Posts and Comments for each post. I'm trying to show the total number of comments for each post on the home page but I can't get the total to show.
Here's my model:
class Post(models.Model):
user = models.ForeignKey(User, on_delete= models.CASCADE)
title = models.CharField(max_length=100, blank=False)
content_text = models.TextField(blank=False, max_length=3000)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Comment(models.Model):
user = models.ForeignKey(User, on_delete= models.CASCADE)
post = models.ForeignKey(Post, on_delete= models.CASCADE)
content_text = models.TextField(max_length=500)
created_date = models.DateTimeField(auto_now_add=True)
My views.py:
def home(request):
posts = Post.objects.all()
return render(request, 'post/home.html', {'posts': posts})
And lastly my html file:
{{ post.comments.count }}
The other information displays correctly such as {{post.title}}
. Any ideas what I'm doing wrong?
Thanks!
Upvotes: 0
Views: 62
Reputation: 88499
Use annotate(...)
as
from django.db.models import Count
def home(request):
posts = Post.objects.annotate(comments_count=Count('comment'))
return render(request, 'post/home.html', {'posts': posts})
and in your template,
{{ post.comments_count }}
Upvotes: 2