我想在Django注释中显示值的名称

时间:2020-01-26 22:07:59

标签: django django-models django-templates django-views

我正在尝试建立一个像应用程序这样的迷你银行,可以进行存款和提款。在其中一个模板中,我想对模型中具有相同货币名称的所有存款和取款进行总计,因此我使用了可以正常工作的注释。 但是我无法在模板中显示货币名称。而是显示1,2,3而不是英镑,美元,欧元。

这是我模型的相关部分:

class Banks(models.Model):
    currency = models.ForeignKey(Currency, blank=True, null=True)
    total_deposits = models.IntegerField(blank=True, null=True)
    total_withdrawals = models.IntegerField(blank=True, null=True)

这是视图:

result = Banks.objects.values('currency'
        ).order_by('currency'
        ).annotate(total_withdrawals=Sum('total_withdrawals')
        ).annotate(total_deposits=Sum('total_deposits')
        )

context = {
        "result": result,
        }

这是模板:

<table class='table'>
          <thead>
            <tr>
              <th class='aligncenter'>#</th>
              <th class='aligncenter'>CURRENCY</th>
              <th class='aligncenter'>TOTAL DEPOSITS</th>
              <th class='aligncenter'>TOTAL WITHDRAWALS</th>
              <th class='aligncenter'>BALANCE</th>
            </tr>
          </thead>
        {% for instance in result %}
            <tr>
              <td class='aligncenter'>{{forloop.counter}}</td>
              <td class='aligncenter'>{{instance.currency}}</td>
              <td class='aligncenter'>{{instance.total_deposits}}</td>
              <td class='aligncenter'>{{instance.total_withdrawals}}</td>
              <td class='aligncenter'>{{instance.total_deposits|sub:instance.total_withdrawals}}</td>
            </tr>
        {% endfor %}
 </table>

这是模板输出: enter image description here

我想在“货币”列下看到货​​币名称。不是1、2和3

1 个答案:

答案 0 :(得分:2)

您应该将货币名称添加到您的值中,可以使用以下方法进行操作:

from django.db.models import F

result = Banks.objects.values(
    'currency',
    currency_name=F('currency__name')
).order_by('currency', 'currency_name').annotate(
    total_withdrawals=Sum('total_withdrawals'),
    total_deposits=Sum('total_deposits')
)

(假设Currency有一个name字段,如果它有一个不同的字段,则可以将该 F('currency__fieldname') fieldname >)。

然后,您可以使用以下方法呈现该图片:

<td class='aligncenter'>{{ instance.currency_name }}</td>

话虽如此,由于您在这里按货币分组,因此简单地注释您的货币就更有意义,例如:

result = Currency.objects.annotate(
    total_withdrawals=Sum('banks__total_withdrawals'),
    total_deposits=Sum('banks__total_deposits')
)

然后,您可以渲染instance, which will call the str(..)on the Currency`对象,例如:

<td class='aligncenter'>{{forloop.counter}}</td>
<td class='aligncenter'>{{ instance }}</td>
<td class='aligncenter'>{{ instance.total_deposits }}</td>
<td class='aligncenter'>{{ instance.total_withdrawals }}</td>
<td class='aligncenter'>{{ instance.total_deposits|sub:instance.total_withdrawals }}</td>