我有一个带有计算余额(运行余额/累积余额)的函数的交易模型,但余额输出作为查询集返回。
<QuerySet [{'id': 1, 'cumsum': -9.0}, {'id': 2, 'cumsum': -16.0},{'id': 3, 'cumsum': -21.0}]>
如何修复我的函数,以便余额仅显示 10 月 16 日为 -9.00、10 月 18 日为 -16.00、然后 10 月 20 日为 -21.00 的数字。先感谢您。
model.py
class Transaction(models.Model):
transaction_date = models.DateField()
account_nickname = models.ForeignKey(Accounts, on_delete=models.CASCADE)
amount = models.FloatField()
@property
def balance(self):
return Transaction.objects.annotate(cumsum=Func(Sum('amount'),template='%(expressions)s OVER (ORDER BY %(order_by)s)',order_by="id")).values('id', 'cumsum').order_by('id', 'cumsum')
views.py
def index(request):
all_transactions = Transaction.objects.all()
context = {
"transactions": all_transactions
}
return render(request,'pages/index.html', context)
索引.html
{% for each_transaction in transactions %}
<tr>
<td>{{each_transaction.transaction_date}}</td>
<td>{{each_transaction.account_nickname}}</td>
<td>{{each_transaction.amount}}</td>
<td>{{each_transaction.balance}}</td>
</tr>
{% endfor %}
输出:
catspeake
相关分类