DecimalField - min_value/max_value properties could be different than decimal type causing unexpected errors · encode/django-rest-framework · Discussion #8963 (original) (raw)

Hello,

It's possible to specify any type value to min_value and max_value properties on DecimalField, that seems to be causing unexpected errors when the type is different than decimal ones.

Consider the following example:

import unittest
from rest_framework import serializers

class DecimalFieldTest(unittest.TestCase):
    def test_decimal_field_1_1(self):
        class CustomSerializer(serializers.Serializer):
            input_num = serializers.DecimalField(min_value=1.1, decimal_places=2, max_digits=4)
        ser = CustomSerializer(data={"input_num": 1.1})
        ser.is_valid(raise_exception=True)

Output:

Running tests...
----------------------------------------------------------------------
E
======================================================================
ERROR [0.008s]: test_decimal_field_1_1
----------------------------------------------------------------------
Traceback (most recent call last):
    ser.is_valid(raise_exception=True)
  File "/root/.local/lib/python3.8/site-packages/rest_framework/serializers.py", line 228, in is_valid
    raise ValidationError(self.errors)
rest_framework.exceptions.ValidationError: {'input_num': [ErrorDetail(string='Ensure this value is greater than or equal to 1.1.', code='min_value')]}

It seems that it is comparing a float value against a decimal one:

>>> 1.1 > decimal.Decimal("1.1")
True

Nevertheless if we pass a decimal type value to min_value, the comparation is performed correctly:

import unittest
import decimal
from rest_framework import serializers


class DecimalFieldTest(unittest.TestCase):
    def test_decimal_field_1_1(self):
        class CustomSerializer(serializers.Serializer):
            input_num = serializers.DecimalField(min_value=decimal.Decimal("1.1"), decimal_places=2, max_digits=4)
        ser = CustomSerializer(data={"input_num": 1.1})
        ser.is_valid(raise_exception=True)
Running tests...
----------------------------------------------------------------------
.
----------------------------------------------------------------------
Ran 1 test in 0.006s

OK

Could not be appropiate to enforce min_value and max_value to be Decimal type to avoid these errors?