在Django中为两种类型的用户分类AbstractUser [英] Subclassing AbstractUser in Django for two types of users

查看:185
本文介绍了在Django中为两种类型的用户分类AbstractUser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django 1.5中开发一个学校数据库系统,并计划将许多不同的用户类型(Student,Staff,Parent)分类为AbstractUser(实际上是AbstractUser的另一个抽象子类)。我只是试图添加一个外部开发的应用程序到我的系统,它使用一个ForeignKey中的用户的一些模型,但是,由于我的用户类型不是用户实例失败。我不能将应用程序模型设置为使用AbstractUser,因为不能对外键使用抽象类。然后我考虑添加到我的settings.py AUTH_USER_MODEL ='myapp.MyUser',并使用设置.AUTH_USER_MODEL代替应用程序中ForeignKey的用户。但是,我有3种不同的用户类型,所以也不能这样做。



较早的原型使用Django 1.4,它不支持自定义用户模型,因此具有引用一个User,但这需要一个额外的连接每个查询,这导致相当复杂的查询。这是我可以继续前进的唯一方法,还是有另一种解决方案?

解决方案

我已经成功地使用了以下解决方案:

1.在models.py中创建 SchoolUser 类,这将是您的 AUTH_USER_MODEL

  TYPES =(('学生','学生'),('员工','员工'),(' ','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):

动态地创建用户对象

如果cls .__名称__。startswith(user.type):#子类的命名约定很重要
return cls(user)
for sub_cls在cls .__子类__()中:
result = sub_cls.factory(user)
如果结果不是无:
返回结果

示例子类(也可以转到users.py文件):

  class StudentUser(UserManager):
def do_something(self):
pass
class StaffUser(UserManager):
def do_something(self):
pass
class ParentUser(UserManager):
def do_s omething(self):
pass

视图是魔术发生的地方;)


  def my_view(request):
school_user = UserManager.factory(request.user)
如果school_user.do_something: #每个类可以有不同的行为

这样你就不需要知道,哪种类型的用户这是,只是实现你的逻辑。

我希望这个很清楚,如果不让我知道!


I'm developing a school database system in Django 1.5, and was planning on having a number of different user types (Student, Staff, Parent) which subclass AbstractUser (actually, another abstract subclass of AbstractUser). I was just attempting to add an externally developed app to my system, which uses User in a ForeignKey for some of its models, however, this fails as my user type is not a 'User' instance. I can't set the apps models to use AbstractUser as one can't use abstract classes for Foreign Keys. I was then considering adding to my settings.py AUTH_USER_MODEL = 'myapp.MyUser' and using settings.AUTH_USER_MODEL in place of User for the ForeignKey in the app. However, I have 3 different user types, so can't do this either.

An earlier prototype used Django 1.4, which did not support custom User models, hence had a reference to a User instead, but this required an extra join for every query, which was leading to quite complex queries. Is this the only way I can go forward with this, or is there another solution?

解决方案

I have successfully used the following solution:
1. Create SchoolUser class in models.py - this will be your AUTH_USER_MODEL class

TYPES = (('Student', 'Student'), ('Staff', 'Staff'), ('Parent', 'Parent'), )
class SchoolUser(AbstractUser):
    type = models.CharField(max_length=10, choices=TYPES, default='Student')

2. Create users.py file and put whole users logic there. Have one abstract class that all others inherit from and which will implement the factory method:

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

Sample children classes (also go to users.py file):

class StudentUser(UserManager):
    def do_something(self):
        pass
class StaffUser(UserManager):
    def do_something(self):
        pass
class ParentUser(UserManager):
    def do_something(self):
        pass

Views is where the magic happens ;)

def my_view(request):
    school_user = UserManager.factory(request.user)
    if school_user.do_something:  # each class can have different behaviour

This way you don't need to know, which type of user it is, just implement your logic.
I hope this is clear enough, if not let me know!

这篇关于在Django中为两种类型的用户分类AbstractUser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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