首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django -> ListView -> get_context_data() -> Model.objects.filter(self.object)

Django -> ListView -> get_context_data() -> Model.objects.filter(self.object)
EN

Stack Overflow用户
提问于 2022-03-31 09:12:49
回答 1查看 498关注 0票数 1

如何从ListView中获取每个模型对象?我有一个博客,我试着按照喜欢的评论数量来排序每个帖子的评论

views.py

代码语言:javascript
复制
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5

def get_context_data(self, *args, **kwargs):
    com = Comment.objects.filter(post=self.object?) #<--- WHAT TO INPUT HERE?
    comment_list = com.annotate(like_count=Count('liked')).order_by('-like_count')

    #BELOW DOESN'T WORK. EVERY POST HAS THE SAME COMMENT LIST AS THE LATEST POST.. SEE PICTURE BELOW
    # posts = Post.objects.all()
    # for post in posts:
    #   com = Comment.objects.filter(post=post) #<--- what to input here
    #   comment_list = com.annotate(like_count=Count('liked')).order_by('-like_count')

    #BELOW DOESN'T WORK. EVERY POST HAS THE SAME COMMENT LIST AS THE LATEST POST.. SEE PICTURE BELOW
    # posts = Post.objects.all()
    # #for post in posts:
    #comment_list = post.comment_set.all().annotate(like_count=Count('liked')).order_by('-like_count')

    context = super(PostListView, self).get_context_data(*args, **kwargs)
    context['cats_menu'] = cats_menu
    context['c_form'] = c_form
    context['comment_list'] = comment_list
    return context

img链接-最新帖子

img链接-所有其他帖子复制最新帖子上的评论。

models.py

代码语言:javascript
复制
class Comment(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
body = models.TextField(max_length=300)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
liked = models.ManyToManyField(Profile, blank=True, related_name='com_likes')

def __str__(self):
    return f"Comment:{self.user}-{self.post}-{self.id}"

def post_id(self):
    return self.post.id

def num_likes(self):
    return self.liked.all().count()

class CommentLike(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
value = models.CharField(choices=LIKE_CHOICES, max_length=8)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return f" | CommentLike({self.user}-{self.comment}-{self.value})"

模板

代码语言:javascript
复制
{% for comment in comment_list %}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-31 11:39:03

您可以使用动态滤波来指定查询集预取对象

视图

代码语言:javascript
复制
class PostListView(ListView):
    model = Post
    template_name = "blog/home.html"
    context_object_name = "posts"
    ordering = ["-date_posted"]
    paginate_by = 5

    def get_queryset(self):
        return (
            super()
            .get_queryset()
            # Prefetch comment using a Prefetch object gives you more control
            .prefetch_related(
                Prefetch(
                    "comment",
                    # Specify the queryset to annotate and order by Count("liked")
                    queryset=Comment.objects.annotate(
                        like_count=Count("liked")
                    ).order_by("-like_count"),
                    # Prefetch into post.comment_list
                    to_attr="comment_list",
                )
            )
        )

模板

代码语言:javascript
复制
{% for post in posts %}
  {% for comment in post.comment_list %}
    {{ comment.like_count }}
  {% endfor %}
{% endfor %}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71689873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档