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

无论如何,是否可以在不实际传递它的情况下执行此操作?类似于它在视图中的工作方式,您可以在其中执行 request.user。

谢谢

有帮助吗?

解决方案

在不传递它的情况下,我见过的最好的方法是使用中间件(在 这个 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())
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top