我想覆盖自定义对象模型管理器以仅返回特定用户创建的对象。管理员用户仍应使用对象模型管理器返回所有对象。
现在我找到了一种可行的方法。他们建议创建您自己的中间件,如下所示:
#### myproject/middleware/threadlocals.py
try:
from threading import local
except ImportError:
# Python 2.3 compatibility
from django.utils._threading_local import local
_thread_locals = local()
def get_current_user():
return getattr(_thread_locals, 'user', None)
class ThreadLocals(object):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
_thread_locals.user = getattr(request, 'user', None)
#### end
在自定义管理器中,您可以调用该get_current_user()
方法以仅返回特定用户创建的对象。
class UserContactManager(models.Manager):
def get_query_set(self):
return super(UserContactManager, self).get_query_set().filter(creator=get_current_user())
这是解决这个用例的好方法吗?这行得通吗?或者这就像“用大锤敲碎坚果”?;-)
只需使用:
Contact.objects.filter(created_by= user)
在每个视图中对我来说都不是很整洁。
编辑不要使用这种中间件方法!!!
使用下面 Jack M. 所述的方法经过一段时间的测试后,这种方法的表现非常奇怪,并且通过这种方法,您将全局状态与当前请求混合在一起。
使用下面介绍的方法。这真的很容易,无需使用中间件。
在您的模型中创建一个自定义管理器,其函数期望当前用户或任何其他用户作为输入。
#in your models.py
class HourRecordManager(models.Manager):
def for_user(self, user):
return self.get_query_set().filter(created_by=user)
class HourRecord(models.Model):
#Managers
objects = HourRecordManager()
#in vour view you can call the manager like this and get returned only the objects from the currently logged-in user.
hr_set = HourRecord.objects.for_user(request.user)
另请参阅有关 middelware 方法的讨论。