Skip to content

Commit

Permalink
add support for decimal fields
Browse files Browse the repository at this point in the history
  • Loading branch information
regiscamimura committed Oct 13, 2023
1 parent df7b8fa commit 832deac
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Profile(models.Model):

boolean = models.BooleanField(blank=True, null=True)
integer = models.IntegerField(blank=True, null=True)
decimal = models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)
json = models.JSONField(blank=True, null=True)
positive_integer = models.PositiveIntegerField(blank=True, null=True)
slug = models.SlugField(blank=True, null=True)
Expand Down
2 changes: 2 additions & 0 deletions tests/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class Meta:
"avatar",
"boolean",
"integer",
"decimal",
"json",
"positive_integer",
"slug",
Expand All @@ -58,6 +59,7 @@ class Meta:
"avatar",
"boolean",
"integer",
"decimal",
"json",
"positive_integer",
"slug",
Expand Down
2 changes: 2 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def profile_view_fixture(db, now, profile_factory, rf):
phone=phone,
boolean=True,
integer=123,
decimal=0.35,
json=dict(something=True),
positive_integer=123,
slug="something",
Expand Down Expand Up @@ -56,6 +57,7 @@ def test_validate_bundle(profile_view):
profile_view.validate_bundle("phone")
profile_view.validate_bundle("boolean")
profile_view.validate_bundle("integer")
profile_view.validate_bundle("decimal")
profile_view.validate_bundle("json")
profile_view.validate_bundle("positive_integer")
profile_view.validate_bundle("slug")
Expand Down
17 changes: 17 additions & 0 deletions worf/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,19 @@ def _validate_positive_int(self, key):
)

return integer

def _validate_decimal(self, key):
value = self.bundle[key]

if value is None or value == "":
return None

try:
decimal = float(value)
except (TypeError, ValueError):
raise ValidationError(f"Field {self.keymap[key]} accepts an decimal")

return decimal

############################################################################
# Public methods for use downstream
Expand Down Expand Up @@ -227,6 +240,10 @@ def validate_bundle(self, key): # noqa: C901
elif isinstance(field, (models.IntegerField, models.SmallIntegerField)):
self.bundle[key] = self._validate_int(key)
return

elif isinstance(field, (models.DecimalField)):
self.bundle[key] = self._validate_decimal(key)
return

elif isinstance(field, models.BooleanField):
self.bundle[key] = self._validate_boolean(key)
Expand Down

0 comments on commit 832deac

Please sign in to comment.