Skip to content

Respect allow_null=True on DecimalFields #7718

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,9 @@ def to_internal_value(self, data):
try:
value = decimal.Decimal(data)
except decimal.DecimalException:
if data == '' and self.allow_null:
return None

self.fail('invalid')

if value.is_nan():
Expand Down Expand Up @@ -1112,6 +1115,12 @@ def validate_precision(self, value):
def to_representation(self, value):
coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING)

if value is None:
if coerce_to_string:
return ''
else:
return None

if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value).strip())

Expand Down
29 changes: 29 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,9 @@ class TestDecimalField(FieldValues):
'2E+1': Decimal('20'),
}
invalid_inputs = (
(None, ["This field may not be null."]),
('', ["A valid number is required."]),
(' ', ["A valid number is required."]),
('abc', ["A valid number is required."]),
(Decimal('Nan'), ["A valid number is required."]),
(Decimal('Snan'), ["A valid number is required."]),
Expand All @@ -1115,6 +1118,32 @@ class TestDecimalField(FieldValues):
field = serializers.DecimalField(max_digits=3, decimal_places=1)


class TestAllowNullDecimalField(FieldValues):
valid_inputs = {
None: None,
'': None,
' ': None,
}
invalid_inputs = {}
outputs = {
None: '',
}
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True)


class TestAllowNullNoStringCoercionDecimalField(FieldValues):
valid_inputs = {
None: None,
'': None,
' ': None,
}
invalid_inputs = {}
outputs = {
None: None,
}
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, coerce_to_string=False)


class TestMinMaxDecimalField(FieldValues):
"""
Valid and invalid values for `DecimalField` with min and max limits.
Expand Down