【问题标题】:Subtracting two fields in a template减去模板中的两个字段
【发布时间】:2012-06-26 02:20:04
【问题描述】:

我试图在模板中循环访问我的数据库中的对象,我想要显示的一件事是表中两个字段之间的差异。有没有一种干净的方法可以做到这一点:

{% for game in games %}
<tr>
    <td width=100><p>{{ game.name }} </p></td>
    <td width=300><p>{{ game.campaign }} </p></td>
    <td width=90><p>{{ game.num_Players }} </p></td>
    <td width=90><p>{{ game.num_Players - game.accepted_Characters }}</p></td>
    <td width=90><p>{{ game.standing_Requests }}</p></td>
</tr>
{% endfor %}

?其中 game 是一个包含所有这些字段的表格对象。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    Django 模板被设计为不进行计算。您应该在视图中调整 games 列表,然后将其显示在模板中:

    # views.py
    for game in games:
        game.chars_diff = game.num_Players - game.accepted_Characters
    
    
    # template.html
    <td><p>{{ game.chars_diff }}</p></td>
    

    【讨论】:

    • 这意味着向表中添加一个新字段还是我可以像您一样添加变量?
    猜你喜欢
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多