32. Ordering by Highest and lowest price

Since the order parameter is now included in the URL, it can be accessed via the request object in our view functions. To implement product sorting on the store page, we need to update the store view function. Before doing so, we will create a new utility function, order_products, within the utility.py file. This function will be responsible for sorting the products according to the specified order.

Note: We opted to implement this functionality in a separate order_products function rather than incorporating it directly into the store view function. This decision was made to prevent the store view function from becoming overly complex and to maintain better organization within our project.

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" :
        products = products
    return products

The order_products function takes two parameters: the order (extracted from the request) and a list of products. It determines the type of ordering specified and sorts the products accordingly. Note that the most-sold condition currently uses a placeholder value. This is due to its more complex implementation, which will be addressed in the following chapter.

In the store view function, add the order variable directly above the context variable. Then, invoke the order_products function with the order parameter and the list of products to sort them accordingly.

Note: Additionally, ensure that the order_products function is imported at the top of the file to make it available for use within the store view function.

importing to views.py
from .utility import filter_product, min_max_price, order_products
views.py\store function
s#! Changing the order of the products
    order = request.GET.get('order') #? gets the parameter value of 'order'
    products = order_products(products, order)
The sorting functionality for the highest and lowest price orders is now functioning as expected.

Last updated