向Django Auth用户模型添加便利方法的最佳方法? [英] Best way to add convenience methods to a Django Auth User model?

查看:116
本文介绍了向Django Auth用户模型添加便利方法的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 django.contrib.auth.models.User 模型中添加一个便利/模型方法。这是最好的做法,因为上次我检查,扩展的用户模型被认为是不好的做法。

I want to add a convenience/model method to the django.contrib.auth.models.User model. What is the best practice for doing this since, last time I checked, extending the User model was considered bad practice.

我有一个单独的定制 UserProfile 模型。我应该把它用于所有用户相关的便利方法吗?

I have a separate custom UserProfile model. Should I be using that for all User-related convenience methods?

推荐答案

这取决于你正在尝试添加到模型中。如果要添加有关用户的更多信息,则通常建议您使用 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)

这篇关于向Django Auth用户模型添加便利方法的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆