From 5b87a27667e64e44dc66bead923bc375b2bf5d0c Mon Sep 17 00:00:00 2001 From: Alexis Lahouze Date: Thu, 25 May 2017 21:23:56 +0200 Subject: [PATCH] improve balances query. --- accountant/models/accounts.py | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/accountant/models/accounts.py b/accountant/models/accounts.py index ceb1467..2db5157 100644 --- a/accountant/models/accounts.py +++ b/accountant/models/accounts.py @@ -30,20 +30,24 @@ class Account(db.Model): def balances(self): """Return the balances of this account.""" return db.session.query( - db.func.sum(Operation.value).label("future"), - db.func.sum( - db.case( - [(Operation.pointed, - Operation.value)], - else_=0 - ) + db.func.coalesce( + db.func.sum( + Operation.value + ), 0 + ).label("future"), + db.func.coalesce( + db.func.sum( + Operation.value + ).filter( + Operation.pointed + ), 0 ).label("pointed"), - db.func.sum( - db.case( - [(Operation.operation_date <= db.func.current_date(), - Operation.value)], - else_=0 - ) + db.func.coalesce( + db.func.sum( + Operation.value, + ).filter( + Operation.operation_date <= db.func.current_date() + ), 0 ).label("current"), ).filter( Operation.account_id == self.id