0

我有一个模型,像这样:

class Action(models.Model): 
    def can_be_applied(self, user):
        #whatever
        return True

我想覆盖它的默认管理器。但我不知道如何将当前用户变量传递给经理,所以我必须这样做:

 [act for act in Action.objects.all() if act.can_be_applied(current_user)]

我如何通过覆盖经理来摆脱它?

谢谢。

4

2 回答 2

2

由于管理器只是方法,你可以在那里传递你想要的任何东西:

class ActionManager(models.Manager):
     def applied(self, user):
         return [x for x in self.get_query_set().all() if x.can_be_applied(user)]

Action.objects.applied(someuser)

尽管效率不高,但它确实可以完成工作。

于 2010-03-08T09:08:48.710 回答
0

这看起来很像已经实现的内容django.contrib.auth: http: //docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_all_permissions

也许您可以看看他们是如何实现该功能的?

于 2010-03-08T09:17:35.970 回答