0

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

类部门资源(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)
4

1 回答 1

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)
于 2013-05-30T16:20:27.657 回答