开发者

Django Custom Managers for User model

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 kn开发者_StackOverflow中文版ow 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....


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜