我正在尝试在模板中将两个变量加在一起,以将两个分数结合在一起并输出值。问题是,当循环进入尚未发生的游戏时,由于变量尚不存在,它将踢出一个错误。
我应该添加什么来跳过循环中没有分数的游戏?
{% for game in games %}
<p class="light-blue text-center">
Total: {{ game.scoreboard.score.home|add:game.scoreboard.score.away }}
</p>
{% endfor %}
我建议在模型中而不是在模板中实现这一点。
因此Score
,例如,如果您有一个模型,则可以将其实现为:
class Score(models.Model):
home = models.IntegerField()
away = models.IntegerField()
@property
def total(self):
return self.home + self.away
然后将其呈现为:
{% for game in games %}
<p class="light-blue text-center">
Total: {{ game.scoreboard.score.total }}
</p>
{% endfor %}
如果数据是字典的结构。您可以使用以下方法在视图中进行预处理:
def my_view(request):
# … some data …
for game in data['games']:
score = game['scoreboard']['score']
score['total'] = score['home'] + score['away']
# …
如果不是所有游戏都有记分板,则可以首先检查它是否是字典中的一个元素:
def my_view(request):
# … some data …
for game in data['games']:
if 'scoreboard' in game and 'score' in game['scoreboard']:
score = game['scoreboard']['score']
score['total'] = score['home'] + score['away']
# …
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句