From dc17058d31aea1ce0d12cd0a20379510d8e4ed4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BE=9D=E7=91=AA=E8=B2=93?= Date: Sun, 19 Jul 2020 19:07:51 +0800 Subject: [PATCH] Replaced the SQL statement in the _find_imbalanced() utility function in the accounting application. --- accounting/views/__init__.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/accounting/views/__init__.py b/accounting/views/__init__.py index 7cd7ef4..5c03f17 100644 --- a/accounting/views/__init__.py +++ b/accounting/views/__init__.py @@ -110,12 +110,12 @@ def _find_imbalanced(records): Args: records (list[Record]): The accounting records. """ - with connection.cursor() as cursor: - cursor.execute("""SELECT transaction_sn - FROM accounting_records - GROUP BY transaction_sn - HAVING SUM(CASE WHEN is_credit THEN -1 ELSE 1 END * amount) != 0""") - imbalanced = [x[0] for x in cursor.fetchall()] + imbalanced = [x.sn for x in Transaction.objects + .annotate( + balance=Sum(Case( + When(record__is_credit=True, then=-1), + default=1) * F("record__amount"))) + .filter(~Q(balance=0))] for record in records: record.is_balanced = record.transaction.sn not in imbalanced