[Answered ]-Creating a price calculator function in a Django model

2πŸ‘

βœ…

So first you should use self instead of OrderService and you need to call the function at some point otherwise your unit_price will not be calculated since the function never got called. The best way to narrow this kinda things down is using print("test price_calc") statements inside the function.

Class OrderService(models.Model):
       article_deadline = models.IntegerField()
       article_pages= models.IntegerField()


       def price_calc(self):
         #print("test price_calc") # check if the function ever gets called
         if self.article_deadline <= 12:
            unit_price = 35
         elif self.article_deadline>= 13 <= 24:
              unit_price= 30
         else:
            unit_price= 25
         return unit_price * self.article_pages

If you want to use the variable name total_cost you can do:

total_cost = price_calc

and register total_cost in the admin / use it in functions, but its the same thing you can as well just use price_calc and it will display/calculate the same value…

You can also see that the function never got called because you should get a Syntax error for if OrderService.article_deadline <= 12. You are missing the β€œ:” here and on the next elif statement as well.

πŸ‘€hansTheFranz

Leave a comment