views:

66

answers:

1

I need to have all my models inherit this manager (Haven't tested this manager and it may be ridiculous so I'm completely open to suggestion/criticism on it as well):

class AccountFilterManager(models.Manager):
    def __init__(self, account=None, *args, **kwargs):
        super(AccountFilterManager, self).__init__(*args, **kwargs)
        self.account = account  # account of course will be an instance of Account(models.Model)

    def get_query_set(self):
        if self.account:
            return super(AccountManager,self).get_query_set().filter(account=self.account)

You can see what I'm trying to do. limit the need to filter out everywhere based on what account I'm dealing with.

What would be the best way to get this manager to work with all my models? Abstract base model with it? Also, how am I going to pass in the account variable into it from the view level? Is this all wrong and evil? I've been trying to find a way to conquer this for a week now :(.

+2  A: 

No. The manager is instantiated as a class attribute, thereby giving all model instances the same manager.

Ignacio Vazquez-Abrams
So, there's no way of passing in the account variable to this from the view or anywhere? (I'm sure you're sick of my questions regarding this. Thanks so much for your answers. You've been really informative in helping me understand how all this fits together.)
orokusaki
The manager is already created by the time `models` is finished importing.
Ignacio Vazquez-Abrams
Oh. Shoot. Well, I'm just about exhausted in my search for the holy grail of DRY filtering based on a current logged in user account. The only way to achieve it apparently is to user threadlocals (which I refuse to do).
orokusaki
Hey, what about Model.add_to_class()? Could that work?
orokusaki
That adds to the whole class. What you *could* do is have a property on the model class that returns a manager that you've already applied `.filter()` to.
Ignacio Vazquez-Abrams