This commit is contained in:
GitHub Merge Button 2011-06-08 12:19:29 -07:00
commit 61e15c041c
2 changed files with 43 additions and 2 deletions

View File

@ -62,6 +62,12 @@ def _model_to_dict(instance, resource=None):
# Method fields
for fname in extra_fields:
if isinstance(fname, (tuple, list)):
fname, fields = fname
else:
fname, fields = fname, False
try:
if hasattr(resource, fname):
# check the resource first, to allow it to override fields
@ -77,7 +83,13 @@ def _model_to_dict(instance, resource=None):
# TODO: It would be nicer if this didn't recurse here.
# Let's keep _model_to_dict flat, and _object_to_data recursive.
data[fname] = _object_to_data(obj)
if fields:
Resource = type('Resource', (object,), {'fields': fields,
'include': (),
'exclude': ()})
data[fname] = _object_to_data(obj, Resource())
else:
data[fname] = _object_to_data(obj)
except NoReverseMatch:
# Ug, bit of a hack for now

View File

@ -2,6 +2,8 @@
from django.test import TestCase
from djangorestframework.resources import _object_to_data
from django.db import models
import datetime
import decimal
@ -28,4 +30,31 @@ class TestObjectToData(TestCase):
def test_datetime(self):
"""datetime objects are left as-is."""
now = datetime.datetime.now()
self.assertEquals(_object_to_data(now), now)
self.assertEquals(_object_to_data(now), now)
def test_tuples(self):
""" Test tuple serialisation """
class M1(models.Model):
field1 = models.CharField()
field2 = models.CharField()
class M2(models.Model):
field = models.OneToOneField(M1)
class M3(models.Model):
field = models.ForeignKey(M1)
m1 = M1(field1='foo', field2='bar')
m2 = M2(field=m1)
m3 = M3(field=m1)
Resource = type('Resource', (object,), {'fields':(), 'include':(), 'exclude':()})
r = Resource()
r.fields = (('field', ('field1')),)
self.assertEqual(_object_to_data(m2, r), dict(field=dict(field1=u'foo')))
r.fields = (('field', ('field2')),)
self.assertEqual(_object_to_data(m3, r), dict(field=dict(field2=u'bar')))