我想覆盖自定义对象模型管理器,以便只返回特定用户创建的对象.管理员用户仍应使用对象模型管理器返回所有对象.
现在我找到了an approach个可以用的.他们建议创建您自己的中间件,如下所示:
#### 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
在Custom管理器中,您可以调用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)
在我看来,每张照片都不是很整洁.
编辑请勿使用此中间件方法!
use the approach stated by Jack M. below经过一段时间的测试后,此方法的行为相当奇怪,并且使用此方法时,您会将全局状态与当前请求混为一谈.
使用下面介绍的方法.这真的很简单,不需要使用中间件.
使用期望当前用户或任何其他用户作为输入的函数在模型中创建自定义管理器.
#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)
另请参阅关于中间件方法的这discussion篇文章.