33. Ordering by most sold products
def total_sales(self) :
items = OrderedItem.objects.filter(order__finished=True, itemstock__product=self.id) #? obtaining the id of that specific item on the stock, as a itemstock contains one product, returns a list of those products
total = sum([item.quantity for item in items])
return totaldef order_products(products, order) :
if order == "highest-price" :
products = products.order_by("-price")
elif order == "lowest-price" :
products = products.order_by("price")
elif order == "most-sold" :
product_list = []
for product in products :
product_list.append((product.total_sales(), product)) #? saved the quantity on the first position of the tuple list since sorted can order it based on the first index
product_list = sorted(product_list, reverse=True, key=lambda tuple: tuple[0])
products = [item[1] for item in product_list] #? grabbing the product from the ordered tuple list
return products
Last updated