From 85b8515a0ab3d72614e0c10100195fa94edfbae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=9D=E7=91=AA=E8=B2=93?= Date: Sat, 18 Jul 2020 08:45:41 +0800 Subject: [PATCH] Simplified the query to get the brought-forward balance in the ledger in the accounting transaction. --- accounting/views/__init__.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/accounting/views/__init__.py b/accounting/views/__init__.py index 1eca81e..707d5ad 100644 --- a/accounting/views/__init__.py +++ b/accounting/views/__init__.py @@ -413,16 +413,12 @@ def ledger(request, subject_code, period_spec): transaction__date__lte=period.end, subject__code__startswith=current_subject.code)) if re.match("^[1-3]", current_subject.code) is not None: - debit = Record.objects.filter( + balance = Record.objects.filter( transaction__date__lt=period.start, - subject__code__startswith=current_subject.code, - is_credit=False).aggregate(sum=Sum("amount")) - credit = Record.objects.filter( - transaction__date__lt=period.start, - subject__code__startswith=current_subject.code, - is_credit=True).aggregate(sum=Sum("amount")) - balance = (0 if debit["sum"] is None else debit["sum"]) \ - - (0 if credit["sum"] is None else credit["sum"]) + subject__code__startswith=current_subject.code)\ + .aggregate(balance=Sum(Case(When( + is_credit=True, then=-1), + default=1) * F("amount")))["balance"] record_brought_forward = Record( transaction=Transaction( date=records[-1].transaction.date),