说我有两个模型发表和评论。我想获取与foreignkey发表的评论相关的评论数。我试图按评论顺序列出帖子。但我不确定如何获取与每个帖子相关的评论数。
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
class Post(models.Model):
title = models.CharField(max_length=100)
和views.py
class PostListView(ListView):
model = Post
template_name = 'community/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
paginate_by = 4
#ordering = ['-#comment'] #how do I do this one?hmm
答案 0 :(得分:0)
我认为您需要这样的东西:
post_pks = Post.objects.all().values('pk', flat=True)
post_comments = {}
for pk in post_pks:
sorted_comments = list(Comment.objects.filter(post_id=pk).ordered_by('-pk'))
post_comments[pk] = sorted_comments
首先,我获取帖子pk并将其循环以获取与它们相关的所有注释。这些注释根据它们的pk排序,我创建了一个字典,其中包含键pks和值注释实例。