我在使用Django-Tastypie制作的API中创建了一个资源,它根据作为url参数提供的哈希值返回单个对象。到目前为止,一切都按预期工作,但资源只返回一个具有单个对象的数组,而不是只返回一个JSON对象。因为我想将资源连接到Backbone-Model,所以只拥有该对象会更方便。
资源:
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回复
[{"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回应通缉:
{"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"}
有关如何实现这一目标的任何指示都将受到高度赞赏。
答案 0 :(得分:2)
您必须使用authorized_read_detail
而不是authorized_read_list
才能检索单个对象而不是包含一个对象的列表。