Django模板-需要使用筛选器()
我有点困了 情况是这样的。我有两个for循环。一个循环遍历类别,另一个循环遍历匹配集。问题是: 我需要从该类别中获取所有匹配项 以下是我所拥有的:Django模板-需要使用筛选器(),django,templates,filter,Django,Templates,Filter,我有点困了 情况是这样的。我有两个for循环。一个循环遍历类别,另一个循环遍历匹配集。问题是: 我需要从该类别中获取所有匹配项 以下是我所拥有的: {% for category in tournament.get_categories %} <div class="line" style="margin-top: 25px; margin-bottom: 40px;"></div> <div class="cont
{% for category in tournament.get_categories %}
<div class="line" style="margin-top: 25px; margin-bottom: 40px;"></div>
<div class="container">
<h3 class="margin-reset" id="{{ category.slug }}">{% trans "Matches schedule" %}<span> | {{ category.name }}</span></h3>
<table class="standard-table table">
<thead>
<tr>
<th>Match</th>
<th>Heure</th>
<th>Plateau</th>
<th>Équipe bleu</th>
<th>Équipe gris</th>
<th>Équipe noir</th>
<th>Résultat</th>
</tr>
</thead>
<tbody>
{% for match in tournament.match_set.filter(category=category) %}
<tr>
<td>{{ match.match_num }}</td>
<td>{{ match.time }}</td>
<td>{{ match.plateau }}</td>
<td><a href="{{ match.blue_team.get_absolute_url }}">{{ match.blue_team.name }}</a></td>
<td><a href="{{ match.grey_team.get_absolute_url }}">{{ match.grey_team.name }}</a></td>
<td><a href="{{ match.black_team.get_absolute_url }}">{{ match.black_team.name }}</a></td>
<td><a href="{{ match.get_absolute_url }}">{{ match.get_url_string }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endfor %}
以及用途:
{{ tournament|get_matches_by_category:category }}
我创建了一个自定义templatetag并使用了该过滤器
这有点过分了,但是……哦,好吧。我在一个非常类似的案例中所做的是将类别列表传递给模板,为它们添加一个带有匹配项的新属性,如:
for category in categories:
category.matches = Match.objects.filter(tournament=tournament, category=category)
这有点慢,但是您可以使用它并减少查询的数量
在此之后,我会将categories列表传递给模板我认为定制的templatetag是这个场景的正确解决方案(这绝对是最简单的解决方案)。你能分享你的代码吗?我很想看看嗨,我不知道。。。我认为这有点过分,因为它只是一个简单的过滤器。我把代码添加到原来的帖子里了。谢谢。我认为这并不过分。这是有道理的,它干净整洁
for category in categories:
category.matches = Match.objects.filter(tournament=tournament, category=category)