1

I had written a function inside models.py which will calculate percentage. But it not showing the calculated values.

I have written a function called 'cal_amount' in models.py performed the calculation. return the value to the model field. But it showing None when i called.

class Course(models.Model):
        price = models.FloatField("Price", blank=True, null=True)
        voucher_id = models.CharField(max_length=255,blank=True, null=True)
        voucher_amount = models.IntegerField(blank=True, null=True)
        discounted_amount = models.IntegerField(blank=True, null=True)
        def __str__(self):  
            return self.course_name

        def cal_amount(self):
             self.discounted_amount = (self.voucher_amount/100)*self.price
             return self.discounted_amount

What i want is calculated amount to be stored in discounted_amount. so i can use {{ obj.discounted_amount }} in html to view it along with actual price. Please suggest me a way.

5
  • Because you do not save object after asignment new value Commented Apr 25, 2019 at 7:29
  • thanks for the reply. you mean like this? data = Course.objects.get(course_name=self.course_name) data.discounted_amount = self.discounted_amount data.save() Commented Apr 25, 2019 at 7:35
  • data = Course.objects.get(course_name=self.course_name) after this data. cal_amount() and then data.save() Commented Apr 25, 2019 at 8:15
  • Why do you want to save this to a field? Just calling a method which returns this calculation when required seems like it would be fine. Commented Apr 25, 2019 at 8:17
  • @DanielRoseman thanks you for your reply. Now its working. Commented Apr 25, 2019 at 8:59

1 Answer 1

1

Instead of a field in the model, you can use a property.

class Course(models.Model):
        price = models.FloatField("Price", blank=True, null=True)
        voucher_id = models.CharField(max_length=255,blank=True, null=True)
        voucher_amount = models.IntegerField(blank=True, null=True)

        def __str__(self):  
            return self.course_name

        @property
        def discounted_amount(self):
             return (self.voucher_amount/100)*self.price


course = Course.objects.get(id=1)
course.discounted_amount # returns the calculated discount

Keep in mind that you are mixing integers with floats to do the calculation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.