aboutsummaryrefslogtreecommitdiff
path: root/ihatemoney/models.py
diff options
context:
space:
mode:
authorDavidRThrashJr <60800614+DavidRThrashJr@users.noreply.github.com>2020-02-17 12:39:51 -0500
committerGitHub <noreply@github.com>2020-02-17 18:39:51 +0100
commit32d76178c0ebe05bddb596f85b283f3f0ee74c85 (patch)
treec587ac56026bf2a1eefa44c6ee225bbe88668c90 /ihatemoney/models.py
parente4f18f0600282b575328b44575aac2bec62bbc17 (diff)
downloadihatemoney-mirror-32d76178c0ebe05bddb596f85b283f3f0ee74c85.zip
ihatemoney-mirror-32d76178c0ebe05bddb596f85b283f3f0ee74c85.tar.gz
ihatemoney-mirror-32d76178c0ebe05bddb596f85b283f3f0ee74c85.tar.bz2
Use SQL statement for summing up weights
* Update models: Bill.pay_each() * Import sql func * reformatted using black * Added ModelsTestCase.test_bill_pay_each() in order to test the SQL query change within pay_each. Had to add Project.ProjectQuery.get_by_name() for the test.
Diffstat (limited to 'ihatemoney/models.py')
-rw-r--r--ihatemoney/models.py13
1 files changed, 11 insertions, 2 deletions
diff --git a/ihatemoney/models.py b/ihatemoney/models.py
index 8a7e273..4d32fd9 100644
--- a/ihatemoney/models.py
+++ b/ihatemoney/models.py
@@ -6,6 +6,7 @@ from flask import g, current_app
from debts import settle
from sqlalchemy import orm
+from sqlalchemy.sql import func
from itsdangerous import (
TimedJSONWebSignatureSerializer,
URLSafeSerializer,
@@ -17,6 +18,9 @@ db = SQLAlchemy()
class Project(db.Model):
+ class ProjectQuery(BaseQuery):
+ def get_by_name(self, name):
+ return Project.query.filter(Project.name == name).one()
id = db.Column(db.String(64), primary_key=True)
@@ -25,6 +29,8 @@ class Project(db.Model):
contact_email = db.Column(db.String(128))
members = db.relationship("Person", backref="project")
+ query_class = ProjectQuery
+
@property
def _to_serialize(self):
obj = {
@@ -388,8 +394,11 @@ class Bill(db.Model):
def pay_each(self):
"""Compute what each share has to pay"""
if self.owers:
- # FIXME: SQL might do that more efficiently
- weights = sum(i.weight for i in self.owers)
+ weights = (
+ db.session.query(func.sum(Person.weight))
+ .join(billowers, Bill)
+ .filter(Bill.id == self.id)
+ ).scalar()
return self.amount / weights
else:
return 0