正如文档中所述,替换用户模型并不罕见:https ://docs.djangoproject.com/es/1.9/topics/auth/customizing/#substituting-a-custom-user-model ,所以,有这个考虑到,最好使用以下代码获取用户模型类:
from django.contrib.auth import get_user_model
UserModel = get_user_model()
之后,您可以使用它UserModel
来添加@Lakshman Prasad 建议的功能:UserModel.add_to_class('get_related_foo_models', get_related_foo_models)
.
为了仅在我更喜欢使用 Django 应用程序配置类(https://docs.djangoproject.com/es/1.9/ref/applications/)时执行代码,所以一个完整的工作示例将是:
# myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'
# myapp/apps.py
from django.apps import AppConfig
from django.contrib.auth import get_user_model
class MyAppConfig(AppConfig):
name = 'myapp'
verbose_name = 'MyApp'
def ready(self):
# Add some functions to user model:
def custom_function(self):
# Do whatsoever
pass
UserModel = get_user_model()
UserModel.add_to_class('custom_function', custom_function)