Tasypie访问get_object_list中的用户对象

时间:2013-05-29 23:25:45

标签: django tastypie

我正在尝试根据当前登录的用户进行过滤。我正在使用ApiKeyAuthentication,据我所知,为了做到这一点,我需要使用get_object_list。我遇到的问题是我似乎无法找到任何方法来访问get_object_list中当前登录的用户。当我尝试调用request.user时,请求对象为空,我似乎无法找到解决问题的答案。

class DepartmentResource(JSONResource):

class Meta:
    resource_name = 'departments'
    list_allowed_methods = ['get', 'put', 'post', 'delete']
    detail_allowed_methods = ['get', 'put', 'post', 'delete']

    authentication = ApiKeyAuthentication()
    authorization = DjangoAuthorization()

def get_object_list(self, request):
    permissions = department_permissions()
    foo = []
    foo.append(ApiObject(permissions.get_departments_linked_to_user(bundle.request.user)))
    return foo

def obj_get_list(self, request=None, **kwargs):
    return self.get_object_list(request)

1 个答案:

答案 0 :(得分:1)

经过大量研究后,我发现我的做法是错误的。 Tastypie有一个名为authorized_read_list的函数,这解决了我的问题,似乎是解决这类问题的理想方法。由于我尝试根据当前登录的用户进行过滤,因此您可以根据当前用户过滤查询。我希望这会为别人节省很多时间。这是我更新的代码:

class FooBarResource(ModelResource):
    class Meta:
        queryset = Foo.objects.all()
        resource_name = 'foobar'
        list_allowed_methods = ['get', 'put', 'post', 'delete']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()

    def authorized_read_list(self, object_list, bundle):
        permissions = department_permissions()
        return object_list.filter(userid=bundle.request.user.id)