【问题标题】:Creating a price calculator function in a Django model在 Django 模型中创建价格计算器功能
【发布时间】:2018-01-09 12:35:45
【问题描述】:

我有这个:

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。我想我错过了一些非常简单的东西。

【问题讨论】:

  • 记住,类中的方法可以自己接受Class属性,如果你使用Pycharm,IDE可以给self对象提示,以后不会出错了。

标签: django python-2.7 django-models django-forms


【解决方案1】:

所以首先你应该使用self 而不是OrderService 并且你需要在某个时候调用该函数,否则你的unit_price 将不会被计算,因为该函数从未被调用过。缩小范围的最好方法是在函数中使用print("test price_calc") 语句。

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

如果你想使用变量名total_cost,你可以这样做:

total_cost = price_calc

并在管理员中注册total_cost/在函数中使用它,但您也可以使用 price_calc,它会显示/计算相同的值...

您还可以看到该函数从未被调用,因为您应该收到if OrderService.article_deadline &lt;= 12 的语法错误。您在此处和下一个 elif 语句中都缺少“:”。

【讨论】:

  • 它给出了一个错误,即 price_calc 正好采用 1 个参数(给定 0)。对此有何建议?到目前为止感谢
  • @MailerDaemon 现在查看代码。它应该可以工作。
  • 感谢它的工作,刚刚返回 unit_price * self.article_pages 然后 total_cost= price_calc
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 2023-02-14
相关资源
最近更新 更多