0

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

完整错误显示:

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

所以我猜 django 正在将整个cleaned_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 方法中执行十进制转换应该是一个问题吗?

谢谢

4

1 回答 1

0

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

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

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

于 2009-06-07T19:24:58.517 回答