MongoDB NumberDecimal:不支持+的操作数类型:“Decimal128”和“Decimal128”

2024-09-28 22:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在玩新的mongodb数据类型NumberDecimal。一般来说,我开发的科学应用程序需要精确(或尽可能精确),所以我想知道如何使用它。在

我正在开发的应用程序之一是python flask应用程序,它从数据库中提取数据并执行各种计算。但是,当我从mongodb中提取一个NumberDecimal(假设是NumberDecimal('24.55'))并尝试将其添加到我在python中创建的bson.decimal128.Decimal128编号中时,我得到以下错误:

TypeError: unsupported operand type(s) for +: 'Decimal128' and 'Decimal128'

如果我试图将NumberDecimal转换为decimal.Decimal(或其他任何东西):

^{pr2}$

所以我想我有几个问题:(1)有没有办法把这个NumberDecimal转换成我在python中可以使用的任何东西,(2)如果没有,有没有一种数据类型可以转换成与NumberDecimal兼容的数据类型,(3)如果没有,在我看来,我可以使用它的唯一方法是使用聚合框架的服务器端(是否还有其他用例)?在


Tags: 数据数据库应用程序flaskmongodb错误科学编号
1条回答
网友
1楼 · 发布于 2024-09-28 22:25:13

似乎需要将Decimal128实例强制转换为标准Python Decimal128实例才能操作它们。但是您应该在create_decimal128_contextbson.decimal128创建的上下文中执行此操作,以确保以后可以将结果存储在数据库中。在

>>> from bson.decimal128 import Decimal128, create_decimal128_context
>>> import decimal
>>>
>>> D128_CTX = create_decimal128_context()
>>>
>>> with decimal.localcontext(D128_CTX):
...     d1 = Decimal128('1.23')
...     d2 = Decimal128('3.21')
...     d3 = Decimal128(d1.to_decimal() + d2.to_decimal())
...
>>> print(d3, type(d3))
4.44 <class 'bson.decimal128.Decimal128'>
>>> print(d3.to_decimal(), type(d3.to_decimal()))
4.44 <class 'decimal.Decimal'>
>>> decimal.Decimal(d3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: conversion from Decimal128 to Decimal is not supported

而且,正如您在上面最后两个命令中看到的,要转换为Python的Decimal类型,请使用Decimal128.to_decimal方法。不要尝试在Decimal128构造函数中传递Decimal128实例。在

在python3.6和pymongo3.4上进行了测试。在

灵感来源于pymongo的documentation模块。在

相关问题 更多 >