From edade3cda740436a89eac053f01e3582fea9d8ee Mon Sep 17 00:00:00 2001 From: Alexis Lahouze Date: Fri, 17 Jul 2015 14:32:47 +0200 Subject: [PATCH] Improve operation query. --- accountant/api/models/operations.py | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/accountant/api/models/operations.py b/accountant/api/models/operations.py index 434059a..0737b69 100644 --- a/accountant/api/models/operations.py +++ b/accountant/api/models/operations.py @@ -58,19 +58,28 @@ class Operation(db.Model): cls, case( whens={cls.canceled: None}, - else_=func.sum(cls.value).over( - partition_by="canceled", - order_by=["operation_date", desc("value"), desc("label")]) + else_=func.sum( + cls.value + ).over( + partition_by=[cls.account_id, cls.canceled], + order_by=["operation_date", desc("value"), desc("label")] + ) ).label("sold") - ).filter(cls.account_id == account_id).order_by( - desc(cls.operation_date), - cls.value, - cls.label, ).subquery() - query = session.query(base_query).select_from(base_query) - query = query.filter(base_query.c.operation_date >= str(begin), - base_query.c.operation_date <= str(end)) + query = session.query( + base_query + ).select_from( + base_query + ).filter( + base_query.c.account_id == account_id, + base_query.c.operation_date >= str(begin), + base_query.c.operation_date <= str(end) + ).order_by( + desc(base_query.c.operation_date), + base_query.c.value, + base_query.c.label, + ) return query