我有一个简单的博客,有 2 个模型:一个用于发布,一个用于评论,如下所示:
class Post(models.Model):
title = models.CharField(max_length=100)
# content = models.TextField()
content = RichTextUploadingField(blank=True, null=True, config_name='claudiu_cfg')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Comment(models.Model):
author = models.CharField(max_length=20)
text = models.TextField(max_length=350)
date_posted = models.DateTimeField(default=timezone.now)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
def __str__(self):
return self.author
我想显示所有帖子(分页)以及每个帖子有多少评论。我的意见.py:
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
就像这样,我得到了所有的帖子,但现在我想用尽可能少的选择访问评论表。我知道这样做的一种方法是定义一个查询集并这样做:
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
queryset = Post.objects.all().prefetch_related()
但是,这不会访问评论数据。
然后我尝试覆盖get_queryset()
函数跳跃以获得所需的结果。仍然没有成功。
def get_queryset(self):
posts = Post.objects.all().prefetch_related('pk__comment').all()
comments = Comment.objects.all().prefetch_related('post')
print(dir(posts))
print('---------------------')
print(posts._prefetch_done)
return posts.order_by('-date_posted')
那仍然行不通,我不明白从这里去哪里。我确实阅读了文档,但这仍然没有帮助我。
请帮忙,因为在 django 方面我没有人可以寻求帮助。
看起来解决方案比我预期的更接近,根据@dirkgroten 的回复,我设法解决了我的问题,如下所示:
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
queryset = Post.objects.all().prefetch_related('comment_set').all()
为了在我的模板中显示评论的数量,我在 for 循环中添加了:
{{ post.comment_set.all|length }}
谢谢你,如果没有你的帮助,如果不是几天的话,我至少要多花几个小时。