我已成功使用以下解决方案:
1. 在 models.py 中创建SchoolUser
类 - 这将是您的AUTH_USER_MODEL
类
TYPES = (('Student', 'Student'), ('Staff', 'Staff'), ('Parent', 'Parent'), )
class SchoolUser(AbstractUser):
type = models.CharField(max_length=10, choices=TYPES, default='Student')
2. 创建 users.py 文件并将整个用户逻辑放在那里。拥有一个所有其他人都继承自并实现工厂方法的抽象类:
class UserManager(object):
def __init__(self, user):
self.user = user
@classmethod
def factory(cls, user):
"""
Dynamically creates user object
"""
if cls.__name__.startswith(user.type): # Children class naming convention is important
return cls(user)
for sub_cls in cls.__subclasses__():
result = sub_cls.factory(user)
if result is not None:
return result
示例子类(也转到 users.py 文件):
class StudentUser(UserManager):
def do_something(self):
pass
class StaffUser(UserManager):
def do_something(self):
pass
class ParentUser(UserManager):
def do_something(self):
pass
视图是魔法发生的地方;)
def my_view(request):
school_user = UserManager.factory(request.user)
if school_user.do_something: # each class can have different behaviour
这样您就不需要知道它是哪种类型的用户,只需实现您的逻辑即可。
我希望这足够清楚,如果不让我知道!