From 253663aee8d0fe04e004daf2d77e9c33feb27b3b Mon Sep 17 00:00:00 2001 From: Alen Mujezinovic Date: Wed, 8 Jun 2011 15:45:04 +0100 Subject: [PATCH 1/2] Added possibility to specify what attributes of ForeignKeys and OneToOne fields to include via nested tuples --- djangorestframework/resources.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/djangorestframework/resources.py b/djangorestframework/resources.py index 36bad9149..4b81bf793 100644 --- a/djangorestframework/resources.py +++ b/djangorestframework/resources.py @@ -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 From cf637e886b9b293e44de55b9f829b738fb286365 Mon Sep 17 00:00:00 2001 From: Alen Mujezinovic Date: Wed, 8 Jun 2011 16:03:01 +0100 Subject: [PATCH 2/2] Nested tuples serialisation test --- djangorestframework/tests/resources.py | 31 +++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/djangorestframework/tests/resources.py b/djangorestframework/tests/resources.py index fd1226be3..088e3159e 100644 --- a/djangorestframework/tests/resources.py +++ b/djangorestframework/tests/resources.py @@ -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) \ No newline at end of file + 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'))) +