AttributeError: 'int' object has no attribute 'quantize'

在阅读《Django by Example》第八章时遇到PayPal支付部分的错误:'int' object has no attribute 'quantize'。问题出在视图views.py中,order.get_total_cost()返回的int类型需要转换为Decimal。错误源于self.price * self.quantity操作,因为DecimalField不支持*运算。尝试在get_total_cost()方法中直接进行Decimal转换,但发现即使转换后,sum求和仍返回int类型。建议在Order类的方法中直接返回Decimal类型值,避免后续使用时忘记转换。
摘要由CSDN通过智能技术生成

在看<<django by example>>的第八章利用paypal付款那里报错

AttributeError: 'int' object has no attribute 'quantize'

错误代码定位提示为views.py

'amount': '%.2f' % order.get_total_cost().quantize(Decimal('.01')),

解决方法很简单将语句改为

'amount': '%.2f' % Decimal(order.get_total_cost()).quantize(Decimal('.01'))

但找到个很有意思的事,可以先看相关语句(只放出了函数语句,和Model的具体语句)

class Product(models.Model):
    price = models.DecimalField(max_digits=10, decimal_places=2)
class Order(models.Model):

    def get_total_cost(self):
        return sum(item.get_cost() for item in self.items.all())

class OrderItem(models.Model):
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField(default=1)

    def get_cost(se
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值