djongo
djongo copied to clipboard
DecimalField inside an ArrayModelField throws a Cannot encode object: Decimal() error
DecimalField inside an ArrayModelField throws a Cannot encode object: Decimal() error when trying to save using Django admin. Here's a custom field to fix the issue -
../fields.py
from bson.decimal128 import Decimal128
from djongo.models import DecimalField
class MongoDecimalField(DecimalField):
def to_python(self, value):
if isinstance(value, Decimal128):
value = self.format_number(value.to_decimal())
return super().to_python(value)
def get_prep_value(self, value):
value = super().get_prep_value(value)
return Decimal128(value)
Sorry found another issue similar to this already. Hence closing.