Skip to content

Commit

Permalink
Fix duration field inspector
Browse files Browse the repository at this point in the history
- Durations should allow min and max to be set
- Durations should be represented as an `openapi.TYPE_STRING` so swagger
  and other tools do not prevent valid input ("00:10:00" is valid, but
  not a number)

See:

https://www.django-rest-framework.org/api-guide/fields/#durationfield and
https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.dateparse.parse_duration
  • Loading branch information
terencehonles committed Feb 22, 2020
1 parent 9ccf24c commit badbb87
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/drf_yasg/inspectors/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,11 +326,16 @@ def find_regex(regex_field):
return pattern


numeric_fields = (serializers.IntegerField, serializers.FloatField, serializers.DecimalField)
comparable_fields = (
serializers.DecimalField,
serializers.DurationField,
serializers.FloatField,
serializers.IntegerField,
)
limit_validators = [
# minimum and maximum apply to numbers
(validators.MinValueValidator, numeric_fields, 'minimum', operator.__gt__),
(validators.MaxValueValidator, numeric_fields, 'maximum', operator.__lt__),
(validators.MinValueValidator, comparable_fields, 'minimum', operator.__gt__),
(validators.MaxValueValidator, comparable_fields, 'maximum', operator.__lt__),

# minLength and maxLength apply to strings
(validators.MinLengthValidator, serializers.CharField, 'min_length', operator.__gt__),
Expand Down Expand Up @@ -391,7 +396,7 @@ def decimal_field_type(field):
(models.DateTimeField, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
(models.DateField, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
(models.DecimalField, (decimal_field_type, openapi.FORMAT_DECIMAL)),
(models.DurationField, (openapi.TYPE_INTEGER, None)),
(models.DurationField, (openapi.TYPE_STRING, None)),
(models.FloatField, (openapi.TYPE_NUMBER, None)),
(models.IntegerField, (openapi.TYPE_INTEGER, None)),
(models.IPAddressField, (openapi.TYPE_STRING, openapi.FORMAT_IPV4)),
Expand All @@ -418,7 +423,7 @@ def decimal_field_type(field):
(serializers.IntegerField, (openapi.TYPE_INTEGER, None)),
(serializers.FloatField, (openapi.TYPE_NUMBER, None)),
(serializers.DecimalField, (decimal_field_type, openapi.FORMAT_DECIMAL)),
(serializers.DurationField, (openapi.TYPE_NUMBER, None)), # ?
(serializers.DurationField, (openapi.TYPE_STRING, None)),
(serializers.DateField, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
(serializers.DateTimeField, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
(serializers.ModelField, (openapi.TYPE_STRING, None)),
Expand Down

0 comments on commit badbb87

Please sign in to comment.