且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向Django Auth用户模型添加便利方法的***方法?

更新时间:2023-12-01 12:28:28

这取决于你正在尝试添加到模型中。如果要添加有关用户的更多信息,则通常建议您使用 UserProfile 方法: http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information -about-users

It depends what you are trying to add to the model. If you want to add more information about the user, then it is generally recommended that you use the UserProfile method: http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

但是,如果您只想将自定义方法或管理器添加到用户模型,我会说,使用代理模型更符合逻辑,如下所示:

However, if you just want to add custom methods or managers to the User model, I would say that it's more logical to use a proxy model, like so:

from django.contrib.auth.models import User

class UserMethods(User):
  def custom_method(self):
    pass
  class Meta:
    proxy=True



User 的任何引用替换为 UserMethods 。 (当然,您可以通过取消注册 User 模型并注册代理模型,从而在管理工具中使用。)

A proxy model will operate on the same database table as the original model, so is ideal for creating custom methods without physically extending the model. Just replace any references to User in your views to UserMethods. (And of course you can use this in the admin tool by unregistering the User model and registering your proxy model in its stead.)

创建的原始用户模型的任何实例都可以通过 UserMethods 模型立即访问,反之亦然。更多资讯: http://docs.djangoproject.com/en / dev / topics / db / models /#proxy-models

Any instances of the original User model that are created will be instantly accessible via the UserMethods model, and vice-versa. More here: http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models

(注意代理模型需要Django 1.1及更高版本)

(NB. Proxy models require Django 1.1 and above)