12
12
import gridfs
13
13
import pymongo
14
14
from bson import SON , Binary , DBRef , ObjectId
15
- from bson .decimal128 import Decimal128
15
+ from bson .decimal128 import Decimal128 , create_decimal128_context
16
16
from bson .int64 import Int64
17
17
from pymongo import ReturnDocument
18
18
@@ -2642,6 +2642,9 @@ def to_mongo(self, document):
2642
2642
2643
2643
2644
2644
class Decimal128Field (BaseField ):
2645
+
2646
+ DECIMAL_CONTEXT = create_decimal128_context ()
2647
+
2645
2648
def __init__ (self , min_value = None , max_value = None , ** kwargs ):
2646
2649
self .min_value = min_value
2647
2650
self .max_value = max_value
@@ -2659,8 +2662,9 @@ def to_mongo(self, value):
2659
2662
return None
2660
2663
if isinstance (value , Decimal128 ):
2661
2664
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 )
2664
2668
return Decimal128 (value )
2665
2669
2666
2670
def to_python (self , value ):
0 commit comments