我已經成功地使用了以下解決方案:
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
這樣你不需要知道,它是哪種類型的用戶,只是實現你的邏輯。
我希望這足夠清楚,如果不讓我知道!