33. Ordering by most sold products

Next, we will implement functionality to order the most sold products. To achieve this, we will add a new method called total_sales within the Product class in the models.py file. This method will calculate and return the total sales for a specific product.

To achieve this, we need to retrieve the quantity of ItemsOrdered where the finished attribute is set to True and match the ID of the specific item in stock, since each ItemStock contains one product. This method will return a list of these products.

models.py\Product
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 total

In the order_products function, we iterate through all the products to calculate each product's total sales. These totals, along with their corresponding product objects, are stored in a list of tuples called product_list. Each tuple contains the total sales as its first element and the product object as its second element. We then sort product_list in descending order based on the total sales values. Finally, we update the original products list to reflect this new order, replacing the product objects with the ones from the sorted product_list.

utility.py
def 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

Note: In the product_list, we utilized a lambda function in the sort to avoid errors in case there are products with the same amount of sales (as the sort function would utilize the second item in the tuple to compare, but it is the product itself).

To test the functionality, navigate to the Orders section of the admin page. Set the Finished checkbox to True for at least one order.

Now, the feature for ordering by the most sold products functions as intended.

Last updated