tomchristie/django-rest-framework — pull request #1195 by chrisconley (2013-10-23 19:06:12+00:00)
Title: Add many_to_native method

Allows serializers to be easily customized when many=True rather than always returning a list of objects.

In our case, we wanted to replicate Stripe's api which returns a similar format to:

```json
{
"object": "customer",
"id": "cus_2o1yHp2LqS4yoo",
"cards": {
"entity": "list",
"url": "/v1/customers/cus_2o1yHp2LqS4yoo/cards",
"data": [
{
"id": "card_2o1yR1PV91qREi",
"object": "card",
"last4": "4242",
"type": "Visa",
}
]
}
}
```

Note that "cards" is an object with "entity", "url" and "data" keys rather than an array.

With this pull req, we can now define our own `many_to_native` method on a serializer superclass. Defining it this way allows top level and all nested lists to be presented in the same way. I looked at other ways of accomplishing the same thing, but this seemed like the cleanest (though I'm fairly new to DRF).

```python
def many_to_native(self, objects):
data = {
'entity': 'list',
'url': self.get_list_url(objects),
'data': [self.to_native(item) for item in objects]
}

return data
```