tags:

views:

106

answers:

2

How would I go about extending the default User model with custom managers?

My app has many user types that will be defined using the built-in Groups model. So a User might be a client, a staff member, and so on. It would be ideal to be able to do something like:

User.clients.filter(name='Test')

To get all clients with a name of Test. I know how to do this using custom managers for user-defined models, but I'm not sure how to go about doing it to the User model while still keeping all the baked-in goodies, at least short of modifying the django source code itself which is a no no....

A: 

You can user Profile for this

AUTH_PROFILE_MODULE = 'accounts.UserProfile'

When a user profile model has been defined and specified in this manner, each User object will have a method -- get_profile() -- which returns the instance of the user profile model associated with that User.

Or you can write your own authenticate backend. Added it in settings

Oduvan
-1 User profiles are good for adding extra data attributes, but they don't help with this case at all. And your final block of code is simply broken (did you test it?), you can't add a manager to a class like that, you have to call the add_to_class method so it is set up correctly.
Carl Meyer
It helps, for using profile module instead User.UserProfile.user_clients.filter(name='Test')But my final block is really broken. Thanks. I am edit my answer.
Oduvan
+1  A: 

Yes, you can add a custom manager directly to the User class. This is monkeypatching, and it does make your code less maintainable (someone trying to figure out your code may have no idea where the User class acquired that custom manager, or where they could look to find it). In this case it's relatively harmless, as you aren't actually overriding any existing behavior of the User class, just adding something new.

from django.contrib.auth.models import User
User.add_to_class('clients', ClientsManager())

If you're using Django 1.1, you could also subclass User with a proxy model; doesn't affect the database but would allow you to attach extra managers without the monkeypatch.

Carl Meyer
helpful, thanks.
Paolo Bergantino