diff --git a/app/fatmodels.py b/app/fatmodels.py index 3b684ad..9f7673f 100644 --- a/app/fatmodels.py +++ b/app/fatmodels.py @@ -1,20 +1,54 @@ -from models import User, Location, Order, OrderItem +from models import User, Location, Order, OrderItem, Product +from sqlalchemy.sql import func, desc -class CountableModel: +class FatModel: + + @classmethod + def all(cls): + return cls.query.all() @classmethod def amount(cls): return cls.query.count() -class FatLocation(Location, CountableModel): pass +class FatLocation(Location, FatModel): pass -class FatOrder(Order, CountableModel): pass +class FatOrder(Order, FatModel): + + # It's hard to add the unique user constraint, + # as DISTINCT seems to apply after a GROUP BY and aggregate + # So DISTINCT ... count(user_id) ... will count all users, + # even if they get reduced by the disctinct afterwards. + @classmethod + def items_per_order(cls): + return Order.query.\ + join(OrderItem).\ + group_by(Order.id).\ + with_entities(Order.id, func.count(OrderItem.user_id).label('total')) -class FatUser(User, CountableModel): pass +class FatUser(User, FatModel): pass -class FatOrderItem(OrderItem, CountableModel): pass +class FatOrderItem(OrderItem, FatModel): pass + + +class FatProduct(Product, FatModel): + + @classmethod + def top4(cls): + top4 = OrderItem.query\ + .join(Product)\ + .join(Location)\ + .group_by(Product.id)\ + .with_entities(Product.name, + Location.name, + func.count(Product.id).label('count') + )\ + .order_by(desc('count'))\ + .limit(4) + for top in top4: + print(top) \ No newline at end of file diff --git a/app/templates/stats.html b/app/templates/stats.html index 035c3c2..454fefa 100644 --- a/app/templates/stats.html +++ b/app/templates/stats.html @@ -4,11 +4,11 @@