Skip to content

Commit bcc4ebf

Browse files
committed
Allow format duration as ISO-8601
1 parent ccfe0a9 commit bcc4ebf

File tree

6 files changed

+54
-7
lines changed

6 files changed

+54
-7
lines changed

docs/api-guide/fields.md

+6-3
Original file line numberDiff line numberDiff line change
@@ -377,13 +377,16 @@ A Duration representation.
377377
Corresponds to `django.db.models.fields.DurationField`
378378

379379
The `validated_data` for these fields will contain a `datetime.timedelta` instance.
380-
The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu]'`.
381380

382-
**Signature:** `DurationField(max_value=None, min_value=None)`
381+
**Signature:** `DurationField(format=api_settings.DURATION_FORMAT, max_value=None, min_value=None)`
383382

383+
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DURATION_FORMAT` settings key, which will be `'standard'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `timedelta` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer.
384384
* `max_value` Validate that the duration provided is no greater than this value.
385385
* `min_value` Validate that the duration provided is no less than this value.
386386

387+
#### `DurationField` format strings
388+
Format strings may either be the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style intervals should be used (eg `'P4DT1H15M20S'`), or the special string `'standard'`, which indicates that Django interval format `'[DD] [HH:[MM:]]ss[.uuuuuu]'` should be used (eg: `'4 1:15:20'`).
389+
387390
---
388391

389392
# Choice selection fields
@@ -552,7 +555,7 @@ For further examples on `HiddenField` see the [validators](validators.md) docume
552555

553556
---
554557

555-
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request). This behavior might change in future, follow updates on [github discussion](https://github.com/encode/django-rest-framework/discussions/8259).
558+
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request). This behavior might change in future, follow updates on [github discussion](https://github.com/encode/django-rest-framework/discussions/8259).
556559

557560
---
558561

docs/api-guide/settings.md

+9
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,15 @@ May be a list including the string `'iso-8601'` or Python [strftime format][strf
314314

315315
Default: `['iso-8601']`
316316

317+
318+
#### DURATION_FORMAT
319+
320+
A format string that should be used by default for rendering the output of `DurationField` serializer fields. If `None`, then `DurationField` serializer fields will return Python `timedelta` objects, and the duration encoding will be determined by the renderer.
321+
322+
May be any of `None`, `'iso-8601'` or `'standard'` (the format accepted by `django.utils.dateparse.parse_duration`).
323+
324+
Default: `'standard'`
325+
317326
---
318327

319328
## Encodings

rest_framework/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
# Default datetime input and output formats
2323
ISO_8601 = 'iso-8601'
24+
STD_DURATION = 'standard'
2425

2526

2627
class RemovedInDRF316Warning(DeprecationWarning):

rest_framework/fields.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from django.utils.dateparse import (
2525
parse_date, parse_datetime, parse_duration, parse_time
2626
)
27-
from django.utils.duration import duration_string
27+
from django.utils.duration import duration_iso_string, duration_string
2828
from django.utils.encoding import is_protected_type, smart_str
2929
from django.utils.formats import localize_input, sanitize_separators
3030
from django.utils.ipv6 import clean_ipv6_address
@@ -1351,9 +1351,11 @@ class DurationField(Field):
13511351
'overflow': _('The number of days must be between {min_days} and {max_days}.'),
13521352
}
13531353

1354-
def __init__(self, **kwargs):
1354+
def __init__(self, format=empty, **kwargs):
13551355
self.max_value = kwargs.pop('max_value', None)
13561356
self.min_value = kwargs.pop('min_value', None)
1357+
if format is not empty:
1358+
self.format = format
13571359
super().__init__(**kwargs)
13581360
if self.max_value is not None:
13591361
message = lazy_format(self.error_messages['max_value'], max_value=self.max_value)
@@ -1376,6 +1378,13 @@ def to_internal_value(self, value):
13761378
self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')
13771379

13781380
def to_representation(self, value):
1381+
output_format = getattr(self, 'format', api_settings.DURATION_FORMAT)
1382+
1383+
if output_format is None or isinstance(value, str):
1384+
return value
1385+
1386+
if output_format.lower() == ISO_8601:
1387+
return duration_iso_string(value)
13791388
return duration_string(value)
13801389

13811390

rest_framework/settings.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from django.core.signals import setting_changed
2525
from django.utils.module_loading import import_string
2626

27-
from rest_framework import ISO_8601
27+
from rest_framework import ISO_8601, STD_DURATION
2828

2929
DEFAULTS = {
3030
# Base API policies
@@ -109,6 +109,8 @@
109109
'TIME_FORMAT': ISO_8601,
110110
'TIME_INPUT_FORMATS': [ISO_8601],
111111

112+
'DURATION_FORMAT': STD_DURATION,
113+
112114
# Encoding
113115
'UNICODE_JSON': True,
114116
'COMPACT_JSON': True,

tests/test_fields.py

+24-1
Original file line numberDiff line numberDiff line change
@@ -1782,8 +1782,31 @@ class TestDurationField(FieldValues):
17821782
field = serializers.DurationField()
17831783

17841784

1785-
# Choice types...
1785+
class TestNoOutputFormatDurationField(FieldValues):
1786+
"""
1787+
Values for `TimeField` with a no output format.
1788+
"""
1789+
valid_inputs = {}
1790+
invalid_inputs = {}
1791+
outputs = {
1792+
datetime.timedelta(1): datetime.timedelta(1)
1793+
}
1794+
field = serializers.DurationField(format=None)
17861795

1796+
1797+
class TestISOOutputFormatDurationField(FieldValues):
1798+
"""
1799+
Values for `TimeField` with a custom output format.
1800+
"""
1801+
valid_inputs = {}
1802+
invalid_inputs = {}
1803+
outputs = {
1804+
datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): 'P3DT08H32M01.000123S'
1805+
}
1806+
field = serializers.DurationField(format='iso-8601')
1807+
1808+
1809+
# Choice types...
17871810
class TestChoiceField(FieldValues):
17881811
"""
17891812
Valid and invalid values for `ChoiceField`.

0 commit comments

Comments
 (0)