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):
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):
__tablename__ = 'purchase_entries'
id = Column(Integer, primary_key=True)

View File

@ -826,14 +826,20 @@ class ShowUserMenu(Menu):
def print_purchased_products(self, user):
products = {}
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
for ref in user.products:
product = ref.product
if product in products:
products[product] += ref.count
else:
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)
if num_products == 0:
print 'No products purchased yet'