Simplified the query in the ledger summary in the accounting application.

This commit is contained in:
依瑪貓 2020-07-18 08:15:54 +08:00
parent 753e69d4e9
commit cb0d42ddd8

View File

@ -23,7 +23,7 @@ from datetime import timedelta
from django.db import connection from django.db import connection
from django.db.models import Sum, Case, When, F from django.db.models import Sum, Case, When, F
from django.db.models.functions import TruncMonth from django.db.models.functions import TruncMonth, Coalesce
from django.http import HttpResponseRedirect, Http404 from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render from django.shortcuts import render
from django.urls import reverse from django.urls import reverse
@ -466,23 +466,18 @@ def ledger_summary(request, subject_code):
if current_subject is None: if current_subject is None:
raise Http404() raise Http404()
# The accounting records # The accounting records
records = [RecordSummary( records = [RecordSummary(**x) for x in Record.objects\
month=x["month"],
debit=x["debit"] if x["debit"] is not None else 0,
credit=x["credit"] if x["credit"] is not None else 0,
balance=x["balance"],
) for x in Record.objects\
.filter(subject__code__startswith=current_subject.code)\ .filter(subject__code__startswith=current_subject.code)\
.annotate(month=TruncMonth("transaction__date"))\ .annotate(month=TruncMonth("transaction__date"))\
.values("month")\ .values("month")\
.order_by("month")\ .order_by("month")\
.annotate( .annotate(
debit=Sum(Case( debit=Coalesce(
When(is_credit=False, then=F("amount"))), Sum(Case(When(is_credit=False, then=F("amount")))),
default=0), 0),
credit=Sum(Case( credit=Coalesce(
When(is_credit=True, then=F("amount"))), Sum(Case(When(is_credit=True, then=F("amount")))),
default=0), 0),
balance=Sum(Case( balance=Sum(Case(
When(is_credit=False, then=F("amount")), When(is_credit=False, then=F("amount")),
default=-F("amount"))))] default=-F("amount"))))]