haldis/app/fatmodels.py

69 lines
1.6 KiB
Python
Raw Normal View History

2019-09-07 23:58:21 +00:00
import typing
2019-05-29 16:02:55 +00:00
from sqlalchemy.sql import desc, func
2016-09-10 14:52:46 +00:00
from hlds.definitions import location_definitions
from hlds.models import Location, Dish
from models import Order, OrderItem, User
2016-09-10 14:52:46 +00:00
2016-09-10 21:01:13 +00:00
2019-05-29 16:02:55 +00:00
class FatModel:
2016-09-10 21:01:13 +00:00
@classmethod
def all(cls):
return cls.query.all()
2016-09-10 14:52:46 +00:00
@classmethod
def amount(cls):
return cls.query.count()
2019-05-29 16:02:55 +00:00
class FatLocation(Location, FatModel):
@classmethod
def all(cls):
return location_definitions
@classmethod
def amount(cls):
return len(location_definitions)
2016-09-10 21:01:13 +00:00
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):
2019-09-05 01:33:29 +00:00
return (
2019-09-10 13:17:35 +00:00
Order.query.join(OrderItem).group_by(Order.id)
.with_entities(Order.id,
func.count(OrderItem.user_id).label("total"))
2019-09-05 01:33:29 +00:00
)
2016-09-10 14:52:46 +00:00
2019-05-29 16:02:55 +00:00
class FatUser(User, FatModel):
pass
2016-09-10 14:52:46 +00:00
2019-05-29 16:02:55 +00:00
class FatOrderItem(OrderItem, FatModel):
pass
2016-09-10 14:52:46 +00:00
class FatDish(Dish, FatModel):
2016-09-10 21:01:13 +00:00
@classmethod
2019-09-07 23:58:21 +00:00
def top4(cls) -> None:
2019-09-05 01:33:29 +00:00
top4 = (
OrderItem.query
.join(Order)
.group_by(Order.location_id, OrderItem.dish_id)
2019-09-05 01:33:29 +00:00
.with_entities(
Order.location_id, OrderItem.dish_id, func.count(
OrderItem.dish_id).label("count")
2019-09-05 01:33:29 +00:00
)
.order_by(desc("count"))
2016-09-10 21:01:13 +00:00
.limit(4)
2019-09-05 01:33:29 +00:00
)
2016-09-10 21:01:13 +00:00
for top in top4:
2019-05-29 16:02:55 +00:00
print(top)