mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-26 19:43:59 +03:00
Merge pull request #121 from sebpiq/issue-73
Fixes #73. Thanks @sebpiq, @ekohl!
This commit is contained in:
commit
e8ddbf435c
|
@ -230,13 +230,14 @@ class Serializer(object):
|
|||
# serialize each required field
|
||||
for fname in fields:
|
||||
try:
|
||||
if hasattr(self, smart_str(fname)):
|
||||
# check first for a method 'fname' on self first
|
||||
meth = getattr(self, fname)
|
||||
if inspect.ismethod(meth) and len(inspect.getargspec(meth)[0]) == 2:
|
||||
obj = meth(instance)
|
||||
# we first check for a method 'fname' on self,
|
||||
# 'fname's signature must be 'def fname(self, instance)'
|
||||
meth = getattr(self, fname, None)
|
||||
if (inspect.ismethod(meth) and
|
||||
len(inspect.getargspec(meth)[0]) == 2):
|
||||
obj = meth(instance)
|
||||
elif hasattr(instance, '__contains__') and fname in instance:
|
||||
# check for a key 'fname' on the instance
|
||||
# then check for a key 'fname' on the instance
|
||||
obj = instance[fname]
|
||||
elif hasattr(instance, smart_str(fname)):
|
||||
# finally check for an attribute 'fname' on the instance
|
||||
|
|
|
@ -34,9 +34,7 @@ class TestObjectToData(TestCase):
|
|||
self.assertEquals(self.serialize(Foo().foo), 1)
|
||||
|
||||
def test_datetime(self):
|
||||
"""
|
||||
datetime objects are left as-is.
|
||||
"""
|
||||
"""datetime objects are left as-is."""
|
||||
now = datetime.datetime.now()
|
||||
self.assertEquals(self.serialize(now), now)
|
||||
|
||||
|
@ -121,3 +119,14 @@ class TestFieldNesting(TestCase):
|
|||
|
||||
self.assertEqual(SerializerM2().serialize(self.m2), {'field': {'field1': u'foo'}})
|
||||
self.assertEqual(SerializerM3().serialize(self.m3), {'field': {'field2': u'bar'}})
|
||||
|
||||
def test_serializer_unvalid_hook_method(self):
|
||||
"""
|
||||
Test serializing a model instance with an unvalid hook method on the serializer.
|
||||
"""
|
||||
class SerializerM2(Serializer):
|
||||
fields = ('unvalid_hook', )
|
||||
def unvalid_hook(self):
|
||||
return
|
||||
self.m2.unvalid_hook = 'bla'
|
||||
self.assertEqual(SerializerM2().serialize_model(self.m2), {'unvalid_hook': 'bla'})
|
||||
|
|
Loading…
Reference in New Issue
Block a user