Создание функции калькулятора цен в модели Django

Обновить

April 2019

Просмотры

281 раз

1

У меня есть это:

Class OrderService(models.Model):
       article_deadline = models.IntegerField()
       article_pages= models.IntegerField()
       def price_calc(self):
              if OrderService.article_deadline <= 12
                    unit_price = 35
              elif OrderService.article_deadline>= 13 <= 24
                    unit_price= 30
              else:
                     unit_price= 25
              price_calc()
              return unit_price

        total_cost = article_pages * unit_price

Это дает ошибку, что unit_price не определена. Мне нужно, когда пользователь вводит article_deadline в форме, функция определяет стоимость единицы для использования, а затем вычисляет TOTAL_COST. Я думаю, что я что-то очень простое отсутствует.

1 ответы

1

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.