tomchristie/django-rest-framework — pull request #173 by flashingpumpkin (2012-02-21 13:00:47+00:00)
Title: OnTheFlySerializer should inherit from the user defined resource

Small change involving how things are serialized.

Consider the case that you don't want to return straight serialized lists, but want to wrap them with a dictionary:

```python

{'result': [1,2,3]}
```

This gives you the option to add more metadata to the result, say for example how many items there are in total, what page you're on, the url for the next page of results, etc. Similar to what the `PaginatorMixin` does.

Now, what we often do is add custom methods to the serialization process:

```python

def epoch(dt):
""" Return epoch time for a datetime object or ``None``"""
try:
return int(time.mktime(dt.timetuple()))
except (AttributeError, TypeError):
return None

class EpochMixin(object):
"""
Serializer for ``.datetime`` and ``.pub_date`` attributes on models. Returns
unix timestamps for :obj:`datetime.datetime` objects.
"""
def datetime(self, instance):
return epoch(instance.datetime)
def pub_date(self, instance):
return epoch(instance.pub_date)
```

Considering further how we would normally return that from a view and serialize it via resource:

```python
class MyModelResource(EpochMixin, ModelResource):
model = MyModel
fields = ('datetime', 'pub_date')

class MyModelView(ModelView):
resource = MyModelResource

def get(self, request):
return self.resource.model.objects.all()
```

We get back something like

```python
[{'datetime': 1, 'pub_date':1},{'datetime': 1, 'pub_date':1}]
```

## Problem

Wrapping the result into a dict, the serialization breaks down because the `OnTheFlySerializer` doesn't inherit the methods we mixed into `MyModelResource` via `EpochMixin`.

```python
class MyModelResource(EpochMixin, ModelResource):
model = MyModel
fields = (('result', ('datetime', 'pub_date')),)

class MyModelView(ModelView):
resource = MyModelResource

def get(self, request):
return {'result': self.resource.model.objects.all()}
```
->

```python
{'result': [{'datetime': '2012-02-21 12:56:01.611483', 'pub_date': '2012-02-21 12:56:01.611483'}]}
```

Inheriting dynamically via `type` fixes this and we get back the expected result of

```python
{'result': [{'datetime': 1, 'pub_date': 1}]}
```

Hope that makes sense. :)