django - 在 django 模板中显示银行帐户余额的推荐方法

标签 django django-templates

在 Django 中,我有一个模型,用于记录交易(日期、金额、描述字段)。在我看来,我想显示一个运行平衡,如下所示:

Date       | Description | Amount | Balance
----------------------------------------------
2019-01-01 | Item 1      | $100   | $100
2019-01-02 | Item 2      | -$10   | $90
2019-01-03 | Item 3      | $200   | $290
2019-01-04 | Item 4      | $10    | $300

现在的问题是,BALANCE 当然应该通过将之前的余额与当前的交易相加来计算。对我来说,在 View 内进行此计算似乎最有意义。我不知道还有什么其他合理的方法可以将它放在其他地方。它是否正确?如果是这样,最好的方法是什么?如果不是,处理这个问题的正确方法是什么?

class Transaction(models.Model):
    date = models.DateField()
    amount = models.DecimalField(max_digits=15, decimal_places=2)
    account = models.ForeignKey(BankAccount, on_delete=models.CASCADE)
    description = models.TextField(null=True, blank=True)

在我看来:

transactions = Transaction.objects.filter(account__id=100).order_by("date")

最佳答案

您可以使用 cumsum 来实现此目的。 为了便于理解,我分割了逻辑。

from django.db.models import Window, Sum, F
from django.db.models.functions import Lead

transactions = Transaction.objects.filter(account__id=100).annotate(
    #This will add up 'cumulative_amount' to your instances
    cumulative_amount=Window(Sum('amount'), order_by=F('date').asc())
    #We're now shifting `cumulative_amount`starting with default value
    balance = Lead(expression = 'cumulative_amount', offset=1, default=F('your_default_value')))
)

关于django - 在 django 模板中显示银行帐户余额的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58355446/

相关文章:

django - 我应该如何为使用 South 的 Django 应用程序设置 SOUTH_DATABASE_ADAPTERS?

python - django 1.10 媒体图像不显示

django - 自定义模板标记查询集不返回任何内容

python - 使用 1 个按钮 Django 提交 2 个自定义 Crispy 表单

django - 自定义 DjangoRestFramework 可浏览 API

Django-admin.py startproject --带有模板标签的模板

python - django.db.migrations 是否有 `update migration`(ala South)选项?

python - pydev 无法识别 python 安装与 django

php - 如何访问 Django 中的 http 数组参数?