From 08d4f9663db8f2c31e851509cab5849c2787438b Mon Sep 17 00:00:00 2001 From: Stefan Hackenberg Date: Sun, 28 Jul 2024 11:20:52 +0200 Subject: [PATCH] Improve performance --- coffeebuddy/__init__.py | 2 +- coffeebuddy/model.py | 23 ++++++++++++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/coffeebuddy/__init__.py b/coffeebuddy/__init__.py index abd8ebb..271516c 100644 --- a/coffeebuddy/__init__.py +++ b/coffeebuddy/__init__.py @@ -13,7 +13,7 @@ from flask_sqlalchemy import SQLAlchemy from sqlalchemy.exc import OperationalError -__version__ = "1.1.0" +__version__ = "1.1.1" db = SQLAlchemy() login_manager = flask_login.LoginManager() diff --git a/coffeebuddy/model.py b/coffeebuddy/model.py index fb22ddd..e3e6c3a 100644 --- a/coffeebuddy/model.py +++ b/coffeebuddy/model.py @@ -66,8 +66,18 @@ def drinks_today(self): @property def unpayed(self): - # TODO: Fast enough? - return sum(c.price for c in self.drinks) - sum(p.amount for p in self.pays) + db = flask.current_app.db + return ( + db.session.scalar( + db.select(db.func.sum(Drink.price)).where(Drink.userid == self.id), + ) + or 0.0 + ) - ( + db.session.scalar( + db.select(db.func.sum(Pay.amount)).where(Pay.userid == self.id), + ) + or 0.0 + ) def nth_drink(self, date, n): return ( @@ -129,7 +139,14 @@ def update_bill(self, newbill): def count_selected_manually(self, host: Optional[str] = None) -> int: """Return how often this user logged in using 'Select manually'.""" host = host or socket.gethostname() - return sum(d.selected_manually for d in self.drinks if d.host == host) + db = flask.current_app.db + return db.session.scalar( + db.select(db.func.count("*")).where( + (Drink.userid == self.id) + & (Drink.host == host) + & Drink.selected_manually + ) + ) class Drink(flask.current_app.db.Model):