mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-11 04:07:39 +03:00
Merge cf637e886b
into c7c1408875
This commit is contained in:
commit
61e15c041c
|
@ -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
|
||||
|
|
|
@ -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')))
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user