django - 通过在 django 中的模板上使用过滤器对象获取查询集
问题描述
在模型中:
class Match(models.Model):
hot_league = models.ManyToManyField(HotLeague, blank=True)
class HotLeague(models.Model):
user = models.ManyToManyField(User, blank=True)
price_pool = models.IntegerField()
winner = models.IntegerField()
在视图中:
match = get_object_or_404(Match, pk=pk)
在这里我需要访问这个查询Match
集。
这就是为什么
在模板中:
{% for hot_league in match.hot_league.all %}
通过在模板中编写match.hot_league.all
,我可以获得HotLeague
类的所有查询集。但我想在filter
这里与用户一起使用。就像views
我们可以使用HotLeague.objects.filter(user=request.user)
. 但{% for hot_league in match.hot_league.filter(user=request.user) %}
不适用于模板。
我怎样才能做那种过滤器template
?
解决方案
我怎样才能在模板中做那种过滤器?
故意限制模板以避免这种情况。一些模板处理器,比如Jinja可以进行函数调用,但通常如果你必须这样做,设计就有问题。视图应该确定要呈现的内容,模板应该以良好的格式呈现该内容。
在您看来,您可以将其呈现为:
def some_view(request, pk):
match = get_object_or_404(Match, pk=pk)
hot_leagues = match.hot_league.filter(user=request.user)
return render(
request,
'some_template.html',
{'match': match, 'hot_leagues': hot_leagues}
)
在您的模板中,您可以像这样呈现:
{% for hot_league in hot_leagues %}
<!-- -->
{% endfor %}
推荐阅读
- python - 如何在行为/python中传递参数
- javascript - 为什么在我的情况下返回不结束函数
- flutter - 我如何在 Flutter 中制作这样的选项卡屏幕
- reactjs - 如何动态自定义材料表中的动作图标?
- java - 将图像作为多部分表单数据上传时对 FormDataContentDisposition 进行自定义验证
- kubernetes - Kubernetes 中的端口转发
- python-3.x - scipy.optimize.minimize 中是否需要 ftol 和 gtol 是否适合给它一个非常低的值?
- python - 如何在空间中获得二元组?
- javascript - 与 map 函数相比,使用 JavaScript reduce 的优势
- sql - 增加一列的值