views:

38

answers:

2

Hi there!

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?

Thanks.

A: 

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.

Dmitry Shevchenko
A: 

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?

Olivier