Skip to content

Instantly share code, notes, and snippets.

@ahmedshahriar
Created March 9, 2021 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedshahriar/b1710149b766be5e74ad81c7cd21b8a8 to your computer and use it in GitHub Desktop.
Save ahmedshahriar/b1710149b766be5e74ad81c7cd21b8a8 to your computer and use it in GitHub Desktop.
MongoDecimalField to work with mongdb decimal field using djongo
"""
MongoDecimalField to work with mongdb decimal field using djongo
"""
from bson.decimal128 import Decimal128
from djongo.models import DecimalField
# https://github.com/nesdis/djongo/issues/82
# https://github.com/nesdis/djongo/issues/378
# https://github.com/nesdis/djongo/pull/525/commits/86dbe3918ac4b2299d6aa3249a4509996f53920c
# edit the djongo/operations.py file
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)
"""
usage
example
price = MongoDecimalField(max_length=10, decimal_places=2, blank=True, null=True, max_digits=10, default=Decimal(0.0))
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment