mongoengine: Dict field can't handle python's Decimal

Attempt to save decimal.Decimal object as one of the values in DictField raises bson.errors.InvalidDocument: Cannot encode object: Decimal('20000')

About this issue

  • Original URL
  • State: open
  • Created 10 years ago
  • Comments: 15 (12 by maintainers)

Most upvoted comments

For anyone looking for a quick answer:

from bson.decimal128 import Decimal128

for key in ['decimal_key1', 'decimal_key2']:
    row[key] = Decimal128(row[key])

You need to convert the Decimal to BSON’s Decimal128 before inserting to the database. More info:

https://api.mongodb.com/python/current/api/bson/decimal128.html#module-bson.decimal128

You also require MongoDB 3.4+.

Because as a framework we should be able to deal with Python data types that are being saved to mongo.

It’s not a duplicate. DictField should handle python Decimal’s somehow as they are native Python objects. Arguing about DecimalField is an offtopic remark. I’m no longer interested in MongoEngine and Mongo (and Python)… just my final note here.