【问题标题】:Errors in Decimal Calcs within def clean method?def clean 方法中的十进制计算错误?
【发布时间】:2009-06-07 17:42:12
【问题描述】:

我正在尝试在验证后的 def clean 方法中进行一些简单的计算(基本上是即时吐出检索到的英国产品价格的欧元转换)。我不断收到 TypeError。

完整的错误读取:

无法转换 {'product': , 'invoice': , 'order_discount': Decimal("0.00"), 'order_price': {...}, 'order_adjust': None, 'order_value': None, ' DELETE': False, 'id': 92, 'quantity': 8} 到十进制

所以我猜 django 正在将整个 clean_data 表单传递给 Decimal 方法。不确定我哪里出错了 - 我正在使用的代码是:

def clean_order_price(self):
    cleaned_data = self.cleaned_data
    data = self.data
    order_price = cleaned_data.get("order_price")
    if not order_price:
        try:
            existing_price = ProductCostPrice.objects.get(supplier=data['supplier'], product_id=cleaned_data['product'], is_latest=True)
        except ProductCostPrice.DoesNotExist:
            existing_price = None
        if not existing_price:
            raise forms.ValidationError('No match found, please enter new price')
        else:
            if data['invoice_type'] == 1:
                return existing_price.cost_price_gross
            elif data['invoice_type'] == 2:  
                exchange = EuroExchangeRate.objects.latest('exchange_date')
                calc = exchange.exchange_rate * float(existing_price.cost_price_gross)
                calc = Decimal(str(calc))
                return calc

    return cleaned_data

如果发票是类型 2(欧元发票),则系统应获取最新汇率并将其应用于匹配的英镑价格,以获得欧元结果。

在 def clean 方法中执行十进制转换应该是一个问题吗?

谢谢

【问题讨论】:

  • 我不明白您发布的代码是如何到达十进制的:它在 if/elif 之前无条件地引发异常。请检查并更正缩进?
  • 另外,一旦你进行了编辑:为什么你两次从cleaned_data获得“order_price”,一次用get分配给你然后忽略的变量,一次用[]索引?为什么在某些情况下返回 Decimal 而在其他情况下返回 dict ?这是相当混乱的代码!

标签: django django-forms


【解决方案1】:

我假设您在粘贴时出现缩进错误,if data['invoice_type'] == 1: 中的行实际上应该缩进一级 - 否则,正如 Alex 所说,代码将永远无法进行小数转换。

此代码还有多个其他问题,但最大的问题是最后一行返回整个 clean_data 字典,而不是这个特定字段的值 - 我怀疑这是您看到的错误的原因。

除此之外,通过将cost_price_gross 乘以exchange 来计算calc 存在很大错误。这里exchange 是 EuroExchangeRate 的一个实例,而不是一个数字,所以这个计算不会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多