简体   繁体   English

用户模型的Django自定义管理器

[英]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. 为所有客户端命名为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.... 我知道如何使用自定义管理器为用户定义的模型做到这一点,但我不知道如何继续使用用户模型,同时仍然保留所有的好吃的东西,至少没有修改django源代码本身哪个不是不......

Yes, you can add a custom manager directly to the User class. 是的,您可以直接将自定义管理器添加到User类。 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). 这是monkeypatching,它确实使您的代码不易维护(有人试图找出您的代码可能不知道User类在哪里获得该自定义管理器,或者他们可以找到它的位置)。 In this case it's relatively harmless, as you aren't actually overriding any existing behavior of the User class, just adding something new. 在这种情况下,它相对无害,因为您实际上并没有覆盖User类的任何现有行为,只是添加了一些新的东西。

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 ; 如果您正在使用Django 1.1+,您还可以使用代理模型将 User子类化; doesn't affect the database but would allow you to attach extra managers without the monkeypatch. 不会影响数据库,但会允许您在没有monkeypatch的情况下附加额外的管理器。

You can user Profile for this 您可以为此用户配置文件

AUTH_PROFILE_MODULE = 'accounts.UserProfile' 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. 当以这种方式定义和指定用户配置文件模型时,每个User对象都将有一个方法 - get_profile() - 它返回与该User关联的用户配置文件模型的实例。

Or you can write your own authenticate backend . 或者您可以编写自己的身份验证后端 Added it in settings 在设置中添加它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM