Filtering manager for django model, customized by user
I have a model, smth like this:
class Action(models.Model):
def can_be_applied(self, user):
#whatever
return True
and I want to override its default Manager. But I don't know how to pass the current user variable to the manager, so I have to do smth like this:
[act for act in Action.objects.all() if act.can_be_applied(current_user)]
How do I get rid of it by just overriding the manager?
T开发者_Python百科hanks.
Since managers are just methods, you can pass whatever you want there:
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)
Though not very efficient, it does the job.
This looks a lot like what is already implemented in django.contrib.auth
: http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_all_permissions
Maybe you can take a look at how they implemented that feature?
精彩评论