Search code examples
djangojsonbackbone.jstastypie

Return single object instead of array


I have made a resource in an API made with Django-Tastypie that returns a single object based on a hash value provided as url parameter. So far everything works as expected but instead of returning just a single JSON object the resource returns an array with a single object. As I want to connect the resource to a Backbone-Model it would be much more convenient to have just the object.

Resource:

class ObjectResource(CommonResource):
    class Meta(CommonResource.Meta):
        queryset = ObjectModel.objects.all()
        resource_name = 'object'
        allowed_methods = ['get']
        authorization = Authorization()

    def obj_create(self, bundle, **kwargs):
        return super(ObjectResource, self).obj_create(bundle, hash_value=self.hash_value)

    def authorized_read_list(self, object_list, bundle):
        return object_list.filter(hash_value=self.hash_value)

Json Response

[{"app_enabled": false, "enable_global_note": false, "enable_guest_order_notes": true, "enable_guest_orders": false, "enable_in_house": false, "guest_orders_active": false, "hash_value": "33d96c3c094b54dd918407c3ef79b219", "id": 34, "name": "Spätzlerei", "resource_uri": "", "slug": "spaetzlerei", "state": 0, "time_added": "2013-08-01T20:11:34.689550", "time_modified": "2013-08-06T10:37:01.907677", "vendor": "myorderbird"}]

Json Response Wanted:

{"app_enabled": false, "enable_global_note": false, "enable_guest_order_notes": true, "enable_guest_orders": false, "enable_in_house": false, "guest_orders_active": false, "hash_value": "33d96c3c094b54dd918407c3ef79b219", "id": 34, "name": "Spätzlerei", "resource_uri": "", "slug": "spaetzlerei", "state": 0, "time_added": "2013-08-01T20:11:34.689550", "time_modified": "2013-08-06T10:37:01.907677", "vendor": "myorderbird"}

Any pointers on how to achieve this would be highly appreciated.


Solution

  • You have to use authorized_read_detail instead of authorized_read_list in order to retrieve a single object instead of a list with one object.