Question

By default, when using django-tastypie and fetching a resource list, the response is of the format:

{
    "meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 3
    },
    "objects": [{
        "body": "Welcome to my blog!",
        "id": "1",
        "pub_date": "2011-05-20T00:46:38",
        "resource_uri": "/api/v1/entry/1/",
        "slug": "first-post",
        "title": "First Post",
        "user": "/api/v1/user/1/"
    },
    ...
    ]
}

I've dug into the documentation and looked & looked, but I can't seem to find any kind of meta option or setting to change the "objects" key to actually describe the returned items. For example, let's say I have list of locations in one api call and a list of people in another. I'd like to be able to differentiate the key to "locations" and "people". The real reason for this is because I'm using RestKit on iOS and want to be able to set up multiple mappings.

Was it helpful?

Solution

The Resource hooks alter_* can be used to alter the structure of the data.

An example Resource using 'locations' would be:

class MyLocationsResource(ModelResource):
    def alter_list_data_to_serialize(self, request, data):
        data['locations'] = data['objects']
        del data['objects']
        return data

    def alter_deserialized_list_data(self, request, data):
        data['objects'] = data['locations']
        del data['locations']
        return data
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top