Reputation: 65
So I am building an e-commerce website to advance my knowledge in python . So far my learning curve is going good . I am wondering on how to calculate cart total .
I have my product model
def Products(models.Model):
price=models.Decimalfield(default=2.50,null=True,decimal_places=2)
quantity=models.InterField(default=4,null=True)
def Cart(models.Model):
total=models.DecimalField(default=0.0,decimal_places=2)
products=models.ManyToManyField(Products,null=True)
Lets assume a user added 2 products in the cart
First product
Product.quantity=3, Product.price=$40
Second Product
Product.quantity=5, Product.price=$20
What will be the best way to calculate my cart total.
I tried this, I created a save function under the cart model
def save(self,*args,**kwargs):
if self.id:
total=0.00
products=self.products.all()
total=math.fsum(pro.price * pro.quantity for pro in products)
self.total=total
super(Cart,self).save(*args,**kwargs)
But this does not work out for me, please I need help. Thanks in Advance
Upvotes: 0
Views: 634
Reputation: 65
The code is working perfectly, i had a typo error for the field. Thanks guys for the contribution.
Upvotes: 1