【问题标题】:How to pass a decimal value when making a post request in django?在 django 中发出 post 请求时如何传递十进制值?
【发布时间】:2021-08-17 05:28:36
【问题描述】:

我正在尝试向第三方应用程序发出发布请求以及一些数据,并且数据还具有最多两点的十进制值,这是我从数据库 (order.amount) 中获取的,但是在发出请求之后错误说数据不可序列化为 json 然后我将其传递为 '"%s"' % round(order.amount,2) 然后也收到错误帖子数据为空。寻找解决此问题的建议。

    request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2) 
    transferId=transfer_identifier,remarks="Test transfer")

    getting error: decimal is not json serializable

    print('"%s"' % round((order.amount),2) #"5000.23"
    
    request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
    
    getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"}
    
    
    but when hardcoding amount then it is working
    request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer")

【问题讨论】:

    标签: json python-3.x django django-rest-framework decimal


    【解决方案1】:

    注意这一行,

    print('"%s"' % round((order.amount),2) #"5000.23"
    

    我猜你错过了一件事:你正在格式化你的十进制值,但是你用引号来做这件事,所以你的变量 amount 将包含 "5000.23" 字符串而不是 5000.23

    所以,看:

    request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
    

    你有amount='"5000.23"',这些引号妨碍了序列化。

    要修复它,只需删除额外的引号:

    print('%s' % round((order.amount),2) # '5000.23'
    
    request = Transfer.request_transfer(beneId=beneficiary_id, amount='%s' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
    

    【讨论】:

    • 非常感谢@FedorIvanov 它成功了。这是一个气味错误,从昨天开始我就被困在这个问题上。
    【解决方案2】:

    根据Python docsround函数:

    如果ndigits 被省略或None,则返回值是一个整数。 否则返回值的类型与 number 相同。

    因此,round 在传递 Decimalndigits 时将返回 Decimal,因此传递 amount=round((order.amount),2) 不会按照您的假设进行(转换为 floatint)。同样将Decimal 转换为float 意味着我们想要的精度损失(我们将使用Decimal 的全部原因)。要传递 Decimal 值,只需将其作为 string 传递(这当然意味着我们需要在客户端执行一些类型转换,如果我们想使用它进行算术运算):

    request = Transfer.request_transfer(
        beneId=beneficiary_id,
        amount=str(order.amount),
        transferId=transfer_identifier,
        remarks="Test transfer"
    )
    

    【讨论】:

    • 感谢@AbdulAzizBarkat 的回复。我使用了round 函数,因为第3 方应用程序已经提到他们接受小数点后两位的金额,所以如果我执行str(order.amount) 那么它就变成了字符串,但值为 50000.1235,不符合第 3 方应用说明
    • @AmitYadav 然后使用str(round(order.amount, 2))
    • 我也试过了,但遇到了同样的错误。现在解决了,我写的是 ' "%s" ' % round((order.amount),2) 而不是 '%s' % round((order.amount),2)。不过非常感谢您的建议。
    猜你喜欢
    • 2021-05-25
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 2015-07-21
    • 2018-03-26
    • 1970-01-01
    相关资源
    最近更新 更多