3

我想在我写的自定义管理器中访问当前登录的用户。我想这样做,以便我可以过滤结果以仅显示他们有权访问的对象。

有没有在没有实际传递的情况下这样做?类似于它在可以执行 request.user 的视图中的工作方式。

谢谢

4

1 回答 1

6

在不传递它的情况下,我见过的最好的方法是使用中间件(在这个 StackOverflow 问题中描述,我将复制/粘贴以方便参考):

中间件:

try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

def get_current_user():
    return getattr(_thread_locals, 'user', None)

class ThreadLocals(object):
    def process_request(self, request):
        _thread_locals.user = getattr(request, 'user', None)

经理:

class UserContactManager(models.Manager):
    def get_query_set(self):
        return super(UserContactManager, self).get_query_set().filter(creator=get_current_user())
于 2010-02-16T20:55:11.463 回答