diff options
| author | James Cleveland | 2013-01-15 13:02:53 +0000 |
|---|---|---|
| committer | James Cleveland | 2013-01-15 13:08:52 +0000 |
| commit | 4fc3b1ba56239a1fb999f9aef99cdbcfbc9aa254 (patch) | |
| tree | 9a0aac863f3bfe8064879b19426098d9d9c8779f /rest_framework/utils | |
| parent | da6b9576c5c5f019800555108fc86887ef7e453d (diff) | |
| download | django-rest-framework-4fc3b1ba56239a1fb999f9aef99cdbcfbc9aa254.tar.bz2 | |
Add timedelta encoder to the JSONEncoder class.
Whilst this commit adds *encoding* of timedeltas to a string of a floating
point value of the seconds, you must add your own serializer field for
whatever timedelta model field you are using. This is because Django doesn't
support any kind of timedelta field out-of-the-box, so you have to either
implement your own or use django-timedelta.
If this is the case and you want to serialise timedelta input, you will have
to implement your own special field to use for the timedelta, which is not
included in core as it is based on a 3rd party library. Here is an example:
import datetime
import timedelta
from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from rest_framework.fields import WritableField
class TimedeltaField(WritableField):
type_name = 'TimedeltaField'
form_field_class = forms.FloatField
default_error_messages = {
'invalid': _("'%s' value must be in seconds."),
}
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
try:
return datetime.timedelta(seconds=float(value))
except (TypeError, ValueError):
msg = self.error_messages['invalid'] % value
raise ValidationError(msg)
Which is based on the FloatField. This field can then be used in
your serializer like this:
from yourapp.fields import TimedeltaField
class YourSerializer(serializers.ModelSerializer):
duration = TimedeltaField()
Diffstat (limited to 'rest_framework/utils')
| -rw-r--r-- | rest_framework/utils/encoders.py | 4 |
1 files changed, 3 insertions, 1 deletions
diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index c70b24dd..7afe100a 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -12,7 +12,7 @@ from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata class JSONEncoder(json.JSONEncoder): """ - JSONEncoder subclass that knows how to encode date/time, + JSONEncoder subclass that knows how to encode date/time/timedelta, decimal types, and generators. """ def default(self, o): @@ -34,6 +34,8 @@ class JSONEncoder(json.JSONEncoder): if o.microsecond: r = r[:12] return r + elif isinstance(o, datetime.timedelta): + return str(o.total_seconds()) elif isinstance(o, decimal.Decimal): return str(o) elif hasattr(o, '__iter__'): |
