A_K
A_K

Reputation: 902

Adding taxes to a total function in Django

I have made a model for a cart with products in it

I just added taxes in the model with a default of 0.14 (as an example in order to change it every time an order is made) I am unable to write it in a function that reads from this model and is multiplied by the taxes percentage.

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    ordered = models.BooleanField(default=False)
    taxes = models.FloatField(default=0.14)

    def __str__(self):
        return self.user.username

    def get_total(self):
        total = 0
        amount = models.FloatField()
        for order_item in self.items.all():
            total += order_item.get_final_price()
        if self.coupon:
            total -= self.coupon.amount
        return total

Upvotes: 1

Views: 100

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

You multiply the result of the get_total() method call with 1+self.taxes, so:

class Order(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    items = models.ManyToManyField(OrderItem)
    ordered = models.BooleanField(default=False)
    taxes = models.FloatField(default=0.14)

    def __str__(self):
        return self.user.username

    def grand_total(self):
        return self.get_total() * (1 + self.taxes)

    def get_total(self):
        total = 0
        amount = models.FloatField()
        for order_item in self.items.all():
            total += order_item.get_final_price()
        if self.coupon:
            total -= self.coupon.amount
        return total

Upvotes: 2

Related Questions