Skip to content

Commit

Permalink
Merge pull request #2549 from bagerard/fix_decimal_field_precision0
Browse files Browse the repository at this point in the history
Fix decimal field precision0
  • Loading branch information
bagerard committed Aug 7, 2021
2 parents bb9ba73 + 0af96b1 commit 8b5cf9e
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 3 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,4 @@ that much better:
* Felix Schultheiß (https://github.com/felix-smashdocs)
* Jan Stein (https://github.com/janste63)
* Timothé Perez (https://github.com/AchilleAsh)
* oleksandr-l5 (https://github.com/oleksandr-l5)
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Development
- (Fill this out as you fix issues and develop your features).
- EnumField improvements: now `choices` limits the values of an enum to allow
- Fix deepcopy of EmbeddedDocument #2202
- Fix error when using precision=0 with DecimalField #2535

Changes in 0.23.1
===========
Expand Down
13 changes: 10 additions & 3 deletions mongoengine/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,10 @@ def __init__(
self.min_value = min_value
self.max_value = max_value
self.force_string = force_string

if precision < 0 or not isinstance(precision, int):
self.error("precision must be a positive integer")

self.precision = precision
self.rounding = rounding

Expand All @@ -482,9 +486,12 @@ def to_python(self, value):
value = decimal.Decimal("%s" % value)
except (TypeError, ValueError, decimal.InvalidOperation):
return value
return value.quantize(
decimal.Decimal(".%s" % ("0" * self.precision)), rounding=self.rounding
)
if self.precision > 0:
return value.quantize(
decimal.Decimal(".%s" % ("0" * self.precision)), rounding=self.rounding
)
else:
return value.quantize(decimal.Decimal(), rounding=self.rounding)

def to_mongo(self, value):
if value is None:
Expand Down
20 changes: 20 additions & 0 deletions tests/fields/test_decimal_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,23 @@ class Person(Document):
assert 2 == Person.objects(money__gt="7").count()

assert 3 == Person.objects(money__gte="7").count()

def test_precision_0(self):
"""prevent regression of a bug that was raising an exception when using precision=0"""

class TestDoc(Document):
d = DecimalField(precision=0)

TestDoc.drop_collection()

td = TestDoc(d=Decimal("12.00032678131263"))
assert td.d == Decimal("12")

def test_precision_negative_raise(self):
"""prevent regression of a bug that was raising an exception when using precision=0"""
with pytest.raises(
ValidationError, match="precision must be a positive integer"
):

class TestDoc(Document):
dneg = DecimalField(precision=-1)

0 comments on commit 8b5cf9e

Please sign in to comment.