python - 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”是一个查询集而不是一个值。我怎样才能做到这一点?
解决方案
在您的模板中,您可以通过以下方式访问相关对象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 %}
推荐阅读
- sass - 根据使用的 sass mixin 将生成的 css 代码从 scss 源拆分为多个 css 文件
- ajax - 流程图上的 Json 返回结果图
- url - 在 URL power Bi 中应用过滤器
- go - 如何返回第一个http响应以回答
- google-cloud-platform - Stackdriver IoT 设备监控
- angular - 我想让这个角度代码返回多个结果而不是一个
- azure-active-directory - 将 Azure 服务管理 REST API 用作已注册的 Active Directory 应用程序
- visual-studio-2019 - Visual Studio 2019 预览版 - 自动完成未选择第一个或任何选项
- python - Pandas 数据框捕获具有多个列的行,其中填充了常量
- wordpress - 在 Wordpress 单个博客文章中的“the_title”之后和“the_content”之前放置一个片段