【问题标题】:Django sql error in view but not via adminDjango sql错误在视图中但不是通过管理员
【发布时间】:2021-08-02 06:40:34
【问题描述】:

我收到unsupported operand type(s) for +: 'float' and 'decimal.Decimal' 错误。当我在我的 update_account 函数中调试我的代码时,我可以看到 instance.amount 是 <class 'float'> 而 a.balance 是 <class 'decimal.Decimal'> 所以这个错误是有道理的。现在,如果我要在我的管理页面中手动添加Transaction(user=id, type='deposit', description='Venmo inc', amount=200.00),代码不会引发错误。两种类型都是<class 'decimal.Decimal'>。为什么通过我的管理员添加交易但通过我的视图添加交易会引发错误?我该如何处理这个错误?

型号:

class Account(models.Model):
    user = models.CharField(max_length=30)
    balance = models.DecimalField(max_digits=500, decimal_places=2)

class Transaction(models.Model):
    user = models.CharField(max_length=30)
    type = models.CharField(max_length=10)
    description = models.CharField(max_length=30)
    amount = models.DecimalField(max_digits=5, decimal_places=2)

@receiver(post_save, sender=Transaction)
def update_account(sender, instance, created, **kwargs):
    if created:
        user = instance.user
        a = Account.objects.get(user=user)
        #error occurs here
        a.balance = instance.amount + a.balance 
        a.save()

查看:

def transaction(request):
    id = request.user.id
    t = Transaction(user=id, type='deposit', description='Venmo inc', amount=200.00)
    t.save()
    return HttpResponse('Transaction Complete')

【问题讨论】:

    标签: python sql django model


    【解决方案1】:

    很可能是因为 django 管理员知道数据库字段的类型并进行内部转换。你的观点没有那么聪明,你需要将浮点数强制为小数

    
    from decimal import Decimal
    
    # Quick and dirty hack
    def transaction(request):
        id = request.user.id
        t = Transaction(user=id, type='deposit', description='Venmo inc', amount=Decimal(200.00))
        t.save()
        return HttpResponse('Transaction Complete')
    

    更好的方法是在模型的 save() 方法中检查金额是否为浮点数,如果不是,则将其转换。

    【讨论】:

    • 酷,感谢您的解释和快速修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2018-04-24
    相关资源
    最近更新 更多