[1.8.x] Fixed #25019 -- Added UUID support in DjangoJSONEncoder

Backport of 6355a6d4f5 and 2e05ef4e18 from master.
This commit is contained in:
Lukas Hetzenecker 2015-06-23 22:56:22 +02:00 committed by Claude Paroz
parent 0db2cdb1fa
commit ebcfedb0e5
3 changed files with 12 additions and 2 deletions

View File

@ -8,6 +8,7 @@ from __future__ import absolute_import, unicode_literals
import datetime import datetime
import decimal import decimal
import json import json
import uuid
import sys import sys
from django.core.serializers.base import DeserializationError from django.core.serializers.base import DeserializationError
@ -86,7 +87,7 @@ def Deserializer(stream_or_string, **options):
class DjangoJSONEncoder(json.JSONEncoder): class DjangoJSONEncoder(json.JSONEncoder):
""" """
JSONEncoder subclass that knows how to encode date/time and decimal types. JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
""" """
def default(self, o): def default(self, o):
# See "Date Time String Format" in the ECMA-262 specification. # See "Date Time String Format" in the ECMA-262 specification.
@ -108,6 +109,8 @@ class DjangoJSONEncoder(json.JSONEncoder):
return r return r
elif isinstance(o, decimal.Decimal): elif isinstance(o, decimal.Decimal):
return str(o) return str(o)
elif isinstance(o, uuid.UUID):
return str(o)
else: else:
return super(DjangoJSONEncoder, self).default(o) return super(DjangoJSONEncoder, self).default(o)

View File

@ -9,4 +9,5 @@ Django 1.8.4 fixes several bugs in 1.8.3.
Bugfixes Bugfixes
======== ========
* ... * Added the ability to serialize values from the newly added
:class:`~django.db.models.UUIDField` (:ticket:`25019`).

View File

@ -6,6 +6,7 @@ import json
import os import os
import pickle import pickle
import unittest import unittest
import uuid
from django.core.exceptions import SuspiciousOperation from django.core.exceptions import SuspiciousOperation
from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers.json import DjangoJSONEncoder
@ -480,6 +481,11 @@ class JsonResponseTests(TestCase):
response = JsonResponse(['foo', 'bar'], safe=False) response = JsonResponse(['foo', 'bar'], safe=False)
self.assertEqual(json.loads(response.content.decode()), ['foo', 'bar']) self.assertEqual(json.loads(response.content.decode()), ['foo', 'bar'])
def test_json_response_uuid(self):
u = uuid.uuid4()
response = JsonResponse(u, safe=False)
self.assertEqual(json.loads(response.content.decode()), str(u))
def test_json_response_custom_encoder(self): def test_json_response_custom_encoder(self):
class CustomDjangoJSONEncoder(DjangoJSONEncoder): class CustomDjangoJSONEncoder(DjangoJSONEncoder):
def encode(self, o): def encode(self, o):