Niladry Kar
Niladry Kar

Reputation: 1203

How to perform multiplication in django model?

This is my model:

class Purchase(models.Model):
    Quantity    = models.PositiveIntegerField()
    rate        = models.DecimalField(max_digits=5,decimal_places=2)
    Amount      = models.DecimalField(max_digits=5,decimal_places=2)

I want to perform multiplication between Quantity and rate and store the result in Amount...

So I have done something like this:

from django.db.models import F

@receiver(pre_save, sender=Purchase)
def update_amount(sender,instance,*args,**kwargs):
    totalamount = Purchase.objects.get(F('rate') * F('Quantity'))
    instance.Amount = totalamount

But its giving me this error:

'CombinedExpression' object is not iterable

Do anyone have any idea how to do this???

Upvotes: 1

Views: 511

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

But here you already have the instance, so the totalamount is simply:

@receiver(pre_save, sender=Purchase)
def update_amount(sender, instance, *args, **kwargs):
    instance.Amount = instance.rate * instance.Quantity

That being said, if the Amount is always the rate multiplied with the Quantity, it is better to define a @property, since then you avoid data duplication, like:

class Purchase(models.Model):

    Quantity    = models.PositiveIntegerField()
    rate        = models.DecimalField(max_digits=5,decimal_places=2)

    def amount(self):
        return self.Quantity * self.rate

Upvotes: 2

Related Questions