Python 显示多对多关系中的对象数?(Django)
我用Django创建了一个简单的博客,每个博客都有帖子和评论。我试图在主页上显示每篇文章的评论总数,但无法显示总数 这是我的模型:Python 显示多对多关系中的对象数?(Django),python,django,Python,Django,我用Django创建了一个简单的博客,每个博客都有帖子和评论。我试图在主页上显示每篇文章的评论总数,但无法显示总数 这是我的模型: class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) title = models.CharField(max_length=100, blank=False) content_text = models.TextField(bl
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})
最后是我的html文件:
{{ post.comments.count }}
其他信息正确显示,如{{post.title}
。知道我做错了什么吗
谢谢 使用注释(…)
作为
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})
从django.db.models导入计数
def home(请求):
posts=Post.objects.annotate(comments\u count=count('comment'))
返回呈现(请求'post/home.html',{'posts':posts})
在你的模板中
{{ post.comments_count }}
{{post.comments\u count}
使用注释(…)
作为
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})
从django.db.models导入计数
def home(请求):
posts=Post.objects.annotate(comments\u count=count('comment'))
返回呈现(请求'post/home.html',{'posts':posts})
在你的模板中
{{ post.comments_count }}
{{post.comments\u count}}
真管用!谢谢你的快速回复。Post.objects.annotate(comments\u count=count('comment'))
是否仍会获取comments计数以及所有其他Post对象?我得多读一点关于……的书。。简而言之,annotate(…)
是类似于AS
的SQLExpression,它可以工作!谢谢你的快速回复。Post.objects.annotate(comments\u count=count('comment'))
是否仍会获取comments计数以及所有其他Post对象?我得多读一点关于……的书。。简而言之,annotate(…)
类似于SQL中的AS
表达式