0

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

Mudits
  • 1,321
  • 2
  • 15
  • 35
ebong
  • 67
  • 9
  • 1
    Code is ok. Maybe you should look into https://docs.djangoproject.com/en/2.1/ref/signals/#post-save https://stackoverflow.com/questions/13014411/django-post-save-signal-implementation – whitehat Mar 07 '19 at 19:31
  • Yes i want to save the total to the field model. – ebong Mar 07 '19 at 19:38
  • What's the error that you get? – Mudits Mar 07 '19 at 19:43
  • Getting no values added to total field. – ebong Mar 07 '19 at 19:43
  • Can you check what you get in `self.id` inside save? I believe its `None` – Mudits Mar 07 '19 at 19:47
  • You are trying to check for `self.id` even before it is saved(committed to the database). Remove it. Instead, try using `post_save` signals. https://stackoverflow.com/questions/13014411/django-post-save-signal-implementation – whitehat Mar 07 '19 at 19:48
  • give me example of the post save. I tried it before, but did not work. How will you use post save in my example – ebong Mar 07 '19 at 19:59

1 Answers1

1

The code is working perfectly, i had a typo error for the field. Thanks guys for the contribution.

ebong
  • 67
  • 9