Created
March 9, 2021 22:03
-
-
Save ahmedshahriar/b1710149b766be5e74ad81c7cd21b8a8 to your computer and use it in GitHub Desktop.
MongoDecimalField to work with mongdb decimal field using djongo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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