首页 > 解决方案 > Queryset 按另一个查询集中的变量过滤

问题描述

我正在尝试通过另一个尚未设置的查询集中的变量过滤查询集。我知道这听起来很混乱,所以让我告诉你。

视图.py

def ViewThreadView(request, thread):
    posts = Post.objects.filter(post_thread=thread)
    thread = Thread.objects.get(pk=thread)
    form_class = QuickReplyForm
    thread_name = thread.name

  
    return render(request, 'thread/viewthread.html',
                  {'thread': thread, 'posts': posts, 'thread_name': thread_name})

后模型

class Post(models.Model):
    post_body = models.TextField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post_date = models.DateTimeField(auto_now_add=True)
    post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id) + ' | ' + str(self.author)

User 模型是标准的 Django 模型

截至目前,如果我想访问模板中的帖子作者,我会这样做

{% for post in posts %}
         post.author
{% endfor %}

我的问题是,如何访问 post.author 的表。因此,如果我想过滤该作者有多少帖子,我想做类似user_posts = Post.objects.get(author=post.author). 但这在视图中不起作用,因为“posts”是一个查询集而不是一个值。我怎样才能做到这一点?

标签: pythondjangodjango-views

解决方案


在您的模板中,您可以通过以下方式访问相关对象post_set

{% for post in posts %}
    {{ post.author.post_set.count }}
{% endfor %}

如果您需要的帖子总数超过帖子总数,您是要过滤相关对象还是其他内容。您始终可以为您的模型编写自定义方法。请参阅模型方法

例如:

from django.utils.functional import cached_property


class Post(models.Model):
    post_body = models.TextField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post_date = models.DateTimeField(auto_now_add=True)
    post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id) + ' | ' + str(self.author)

    @cached_property
    def count_by_author_and_thread(self):
        return self.author.post_set.filter(post_thread=self.post_thread).count()

然后在您的模板中简单使用:

{% for post in posts %}
    {{ post.count_by_author_and_thread }}
{% endfor %}

推荐阅读