Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set the django-tastypie objects key?

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.

like image 545
shawnwall Avatar asked Feb 21 '12 14:02

shawnwall


1 Answers

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
like image 81
josh.bohde Avatar answered Oct 25 '22 02:10

josh.bohde