Skip to content

Commit 98b2a91

Browse files
committed
use create_decimal128_context
1 parent 0e6ca30 commit 98b2a91

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

mongoengine/fields.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import gridfs
1313
import pymongo
1414
from bson import SON, Binary, DBRef, ObjectId
15-
from bson.decimal128 import Decimal128
15+
from bson.decimal128 import Decimal128, create_decimal128_context
1616
from bson.int64 import Int64
1717
from pymongo import ReturnDocument
1818

@@ -2642,6 +2642,9 @@ def to_mongo(self, document):
26422642

26432643

26442644
class Decimal128Field(BaseField):
2645+
2646+
DECIMAL_CONTEXT = create_decimal128_context()
2647+
26452648
def __init__(self, min_value=None, max_value=None, **kwargs):
26462649
self.min_value = min_value
26472650
self.max_value = max_value
@@ -2659,8 +2662,9 @@ def to_mongo(self, value):
26592662
return None
26602663
if isinstance(value, Decimal128):
26612664
return value
2662-
if isinstance(value, (int, float)):
2663-
return Decimal128(str(value))
2665+
if not isinstance(value, decimal.Decimal):
2666+
with decimal.localcontext(self.DECIMAL_CONTEXT) as ctx:
2667+
value = ctx.create_decimal(value)
26642668
return Decimal128(value)
26652669

26662670
def to_python(self, value):

tests/fields/test_decimal128_field.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def test_storage(self):
105105
model = Decimal128Document(dec128_fld=100.0).save()
106106
assert get_as_pymongo(model) == {
107107
"_id": model.id,
108-
"dec128_fld": Decimal128("100.0"),
108+
"dec128_fld": Decimal128("100"),
109109
}
110110

111111
# from Decimal
@@ -124,7 +124,7 @@ def test_storage(self):
124124

125125
def test_json(self):
126126
Decimal128Document.drop_collection()
127-
f = random.random()
127+
f = str(random.random())
128128
Decimal128Document(dec128_fld=f).save()
129129
json_str = Decimal128Document.objects.to_json()
130130
array = json.loads(json_str)

0 commit comments

Comments
 (0)