17.1. Displaying total price
Having displayed the ordered products in the cart, the next step is to display the total price of all items.
To achieve this, we will create a method function named total_price
inside the OrderedItem
class, which will return the total price of the ordered items.
@property
def total_price(self) :
return self.quantity * self.itemstock.product.price
The @property
decorator enables us to call the total_price
function without using parentheses. This is crucial as HTML does not permit the use of parentheses in function calls.
We will now create similar functions, this time to calculate the total price and total quantity of items for the entire order. To accomplish this, we will add method functions named total_quantity
and total_cost
into the Order
class:
@property
def total_quantity(self) :
items_ordered = OrderedItem.objects.filter(order__id = self.id) #? gets all the items of the order
total_quantity = sum([item.quantity for item in items_ordered])
return total_quantity
@property
def total_cost(self) :
items_ordered = OrderedItem.objects.filter(order__id = self.id) #? gets all the items of the order
total_cost = sum([item.total_price for item in items_ordered])
return total_cost
Note: No migration is required as we only need to perform it when creating a new class or directly modifying the attributes of an existing one (changing the status of the database).
Last updated