Merge pull request #2430 from Polyconseil/fbochu/timedelta-json-serialiser-python26-support

Fix timedelta JSON serialization on Python 2.6.
This commit is contained in:
Tom Christie 2015-01-19 12:15:02 +00:00
commit b3a0a2794b
2 changed files with 10 additions and 2 deletions

View File

@ -33,6 +33,14 @@ def unicode_to_repr(value):
return value return value
def total_seconds(timedelta):
# TimeDelta.total_seconds() is only available in Python 2.7
if hasattr(timedelta, 'total_seconds'):
return timedelta.total_seconds()
else:
return (timedelta.days * 86400.0) + float(timedelta.seconds) + (timedelta.microseconds / 1000000.0)
# OrderedDict only available in Python 2.7. # OrderedDict only available in Python 2.7.
# This will always be the case in Django 1.7 and above, as these versions # This will always be the case in Django 1.7 and above, as these versions
# no longer support Python 2.6. # no longer support Python 2.6.

View File

@ -6,7 +6,7 @@ from django.db.models.query import QuerySet
from django.utils import six, timezone from django.utils import six, timezone
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.utils.functional import Promise from django.utils.functional import Promise
from rest_framework.compat import OrderedDict from rest_framework.compat import OrderedDict, total_seconds
from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
import datetime import datetime
import decimal import decimal
@ -41,7 +41,7 @@ class JSONEncoder(json.JSONEncoder):
representation = representation[:12] representation = representation[:12]
return representation return representation
elif isinstance(obj, datetime.timedelta): elif isinstance(obj, datetime.timedelta):
return six.text_type(obj.total_seconds()) return six.text_type(total_seconds(obj))
elif isinstance(obj, decimal.Decimal): elif isinstance(obj, decimal.Decimal):
# Serializers will coerce decimals to strings by default. # Serializers will coerce decimals to strings by default.
return float(obj) return float(obj)