猿问

Django 运行余额/累计余额

我有一个带有计算余额(运行余额/累积余额)的函数的交易模型,但余额输出作为查询集返回。

<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 %}

输出:

绝地无双
浏览 88回答 1
1回答

catspeake

首先删除你的@property balance功能然后在views.pydef index(request):&nbsp; &nbsp; all_transactions = Transaction.objects.annotate(cumsum=Func(Sum('amount'),template='%(expressions)s OVER (ORDER BY %(order_by)s)',order_by="id"))&nbsp; &nbsp; context = {&nbsp; &nbsp; &nbsp; &nbsp; "transactions": all_transactions&nbsp; &nbsp; }&nbsp; &nbsp; return render(request,'pages/index.html', context)然后在你的index.html{% for each_transaction in transactions %}<tr>&nbsp; &nbsp; <td>{{each_transaction.transaction_date}}</td>&nbsp; &nbsp; <td>{{each_transaction.account_nickname}}</td>&nbsp; &nbsp; <td>{{each_transaction.amount}}</td>&nbsp; &nbsp; <td>{{each_transaction.cumsum}}</td></tr>{% endfor %}
随时随地看视频慕课网APP

相关分类

Python
我要回答