问题描述
我想向 django.contrib.auth.models.User
模型添加一个方便/模型方法.这样做的最佳做法是什么,因为上次我检查时,扩展 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
但是,如果您只想向 User
模型添加自定义方法或管理器,我会说使用代理模型更合乎逻辑,如下所示:
from django.contrib.auth.models import User
class UserMethods(User):
def custom_method(self):
pass
class Meta:
proxy=True
创建的原始 User
模型的任何实例都可以通过 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 User 模型的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!