From 0419a23fb85ebbe8ce837be81ae88724bc49c6b6 Mon Sep 17 00:00:00 2001 From: Trang Tran Date: Thu, 26 Oct 2017 08:03:35 +0700 Subject: [PATCH] Adding rounding parameter to DecimalField. --- rest_framework/fields.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9cfd39995..4da3ce735 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -992,12 +992,13 @@ class DecimalField(Field): 'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'), 'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'), 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.'), - 'max_string_length': _('String value too large.') + 'max_string_length': _('String value too large.'), + 'invalid_rounding': _('Invalid rounding option {rounding}. Valid values for rounding are: {valid_roundings}') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None, - localize=False, **kwargs): + localize=False, rounding=None, **kwargs): self.max_digits = max_digits self.decimal_places = decimal_places self.localize = localize @@ -1029,6 +1030,11 @@ class DecimalField(Field): self.validators.append( MinValueValidator(self.min_value, message=message)) + valid_roundings = [v for k, v in vars(decimal).items() if k.startswith('ROUND_')] + if rounding is not None and rounding not in valid_roundings: + self.fail('invalid_rounding', rounding=rounding, valid_roundings=valid_roundings) + self.rounding = rounding + def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal @@ -1121,6 +1127,7 @@ class DecimalField(Field): context.prec = self.max_digits return value.quantize( decimal.Decimal('.1') ** self.decimal_places, + rounding=self.rounding, context=context )