我有一个带有计算余额(运行余额/累积余额)的函数的交易模型,但余额输出作为查询集返回。<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.pyclass 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.pydef 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 %}输出:
1 回答
catspeake
TA贡献1111条经验 获得超0个赞
首先删除你的@property balance功能
然后在views.py
def index(request):
all_transactions = Transaction.objects.annotate(cumsum=Func(Sum('amount'),template='%(expressions)s OVER (ORDER BY %(order_by)s)',order_by="id"))
context = {
"transactions": all_transactions
}
return render(request,'pages/index.html', context)
然后在你的index.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.cumsum}}</td>
</tr>
{% endfor %}
添加回答
举报
0/150
提交
取消