1212import gridfs
1313import pymongo
1414from bson import SON , Binary , DBRef , ObjectId
15- from bson .decimal128 import Decimal128
15+ from bson .decimal128 import Decimal128 , create_decimal128_context
1616from bson .int64 import Int64
1717from pymongo import ReturnDocument
1818
@@ -2642,6 +2642,9 @@ def to_mongo(self, document):
26422642
26432643
26442644class 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 ):
0 commit comments