Optimised product summary to use database (view)

This commit is contained in:
Christoffer Viken 2017-02-10 12:21:59 +00:00
parent 8752cb5b09
commit dd12b05ea2
2 changed files with 25 additions and 8 deletions

11
db.py
View File

@ -66,6 +66,17 @@ class Product(Base):
def __str__(self): def __str__(self):
return self.name return self.name
class UserProducts(Base):
__tablename__ = 'user_products'
user_name = Column(String(10), ForeignKey('users.name'), primary_key=True)
product_id = Column(Integer, ForeignKey("products.product_id"), primary_key=True)
count = Column(Integer)
user = relationship(User, backref=backref('products', order_by=count.desc()), lazy='joined')
product = relationship(Product, backref="users", lazy='joined')
class PurchaseEntry(Base): class PurchaseEntry(Base):
__tablename__ = 'purchase_entries' __tablename__ = 'purchase_entries'
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)

View File

@ -826,14 +826,20 @@ class ShowUserMenu(Menu):
def print_purchased_products(self, user): def print_purchased_products(self, user):
products = {} products = {}
for transaction in user.transactions: for ref in user.products:
if transaction.purchase: product = ref.product
for entry in transaction.purchase.entries: if product in products:
n = entry.product.name products[product] += ref.count
if n in products:
products[n]+=1
else: else:
products[n]=1 products[product] = ref.count
#for transaction in user.transactions:
# if transaction.purchase:
# for entry in transaction.purchase.entries:
# n = entry.product.name
# if n in products:
# products[n]+=1
# else:
# products[n]=1
num_products = len(products) num_products = len(products)
if num_products == 0: if num_products == 0:
print 'No products purchased yet' print 'No products purchased yet'