【发布时间】:2020-01-26 22:07:59
【问题描述】:
我正在尝试建立一个类似于迷你银行的应用程序,我可以在其中进行存款和取款。在其中一个模板中,我想对具有相同货币名称的模型中的所有存款和取款进行汇总,因此我使用 annotate 可以正常工作。 但我无法在模板中显示货币名称。相反,它显示的是 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>
我想在货币列下查看货币名称。不是 1、2 和 3
【问题讨论】:
-
你能分享
Currency的模型吗? -
{{instance.currency}}返回货币 ID(我猜你会覆盖Currency模型中的__str__方法来这样做)。相反,或者更改该模型的__str__方法以返回您在那里为货币名称所拥有的任何字段,或者通过引用该字段{{instance.currency.currency_name_field}}在模板中执行相同操作 -
@Charnel:这是因为
.values(..)。 -
是的,你是对的,因为它是一个 FK,它会返回一个整数。
-
@WillemVanOnsem:这是
Currency模型:class Currency(models.Model):name = models.CharField(max_length=200, default='', blank=True, null=True)symbol = models.CharField(max_length=200, default='', blank=True, null=True)def __unicode__(self):return self.symbol
标签: django django-models django-templates django-views