How do I get Django Rest Framework to round decimals to the maximum precision?
After coercing the input to a Decimal the DecimalField validates the precision of the value in the aptly named, but undocumented, validate_precision
method. So to disable this validation one can override this method and simply return the input value:
class RoundingDecimalField(serializers.DecimalField):
def validate_precision(self, value):
return value
It turns out that doing this is enough to get the desired rounding behaviour.
After calling validate_precision
the DecimalField calls quantize
which will "Quantize the decimal value to the configured precision" (from the docstring).
The rounding mode for this quantisation process is controlled by the current active decimal context.
If a specific rounding mode is desired one can use the (again undocumented) drf_braces.fields.custom.RoundedDecimalField
field from django-rest-framework-braces. This field takes an optional rounding argument where one can specify the desired rounding mode.