首页 > 解决方案 > 通过在 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

标签: djangodjango-modelsdjango-templates

解决方案


我怎样才能在模板中做那种过滤器?

故意限制模板以避免这种情况。一些模板处理器,比如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 %}

推荐阅读