简体   繁体   English

用多个用户身份验证模型替换Django中的用户模型

[英]Substituting the User model in django with more than one user auth model

I am creating an application where it will have two types of users Teacher and Student. 我正在创建一个应用程序,它将具有两种类型的用户教师和学生用户。 Both of them will be able to connect to my portal, but they have different permissions. 他们两个都可以连接到我的门户,但是它们具有不同的权限。 They also have different fields (the teacher has fields about name, field of studies post graduate studies etc, the student has name, name of parents, which classes he is taking etc. ). 他们也有不同的领域(老师有关于姓名的领域,研究生学习的领域等,学生有名字,父母的姓名,他参加的课程等)。 I want to extend the user model and create two types of user as I described above. 我想扩展用户模型并创建两种类型的用户,如上所述。 I ran on this about extending the user model using the AUTH_USER_MODEL and inheriting by AbstractBaseUser thus creating in your app: 我在使用AUTH_USER_MODEL扩展用户模型并由AbstractBaseUser继承,从而在您的应用中创建:

class MyUser(AbstractBaseIser):
    #custom user fields

and by setting 并通过设置

AUTH_USER_MODEL = 'myapp.MyUser'

in the settings file. 在设置文件中。

But if I understand it correctly it can only happen for one custom user. 但是,如果我正确理解它,那么只能对一个自定义用户进行。 Is it better for what I want to just go with 我想随身携带的东西更好吗

user = models.OneToOneField(User)

in my custome user model (eg Teachers)? 在我的自定义用户模型中(例如,教师)? Can AUTH_USER_MODEL except a dictionary to be able to distinguish between two types of users? 除字典外,AUTH_USER_MODEL是否可以区分两种类型的用户? How much affect will have using OneToOneField in performance since the doc says that many joins will have to be performed if you use OneToOnField 使用DocTo表示,如果您使用OneToOnField,将必须执行许多联接,因此使用OneToOneField会对性能产生多大的影响。

Sorry I don't present any of my own code because I haven't written any code yet. 抱歉,我没有提供任何我自己的代码,因为我还没有编写任何代码。 I would like to have this issue cleared for me before implementing something. 我想在执行某些操作之前为我解决此问题。

Keep authentication through MyUser . 通过MyUser保持身份验证。 Do something like this: 做这样的事情:

class UserType(models.Model):
    type = ... # teacher, student, whatever

class MyUser(models.Model):
    name = ...
    username = ...
    user_type = models.ForeignKey('UserType',...

class TeacherProfile(models.Model):
    user = models.ForeignKey('MyUser',...
    user_type = models.ForeignKey('UserType',...
    gradebook = ...

class StudentProfile(models.Model):
    user = models.ForeignKey('MyUser',...
    user_type = models.ForeignKey('UserType',...
    homework = ...

on the MyUser model have a method like: MyUser模型上的方法类似于:

    def get_profile(self):
        if user_type_is_teacher():
            return TeacherProfile.objects.get(user=self, user_type=self.user_type)

so now if you have a student user u you can say 所以现在如果你有一个学生用户u可以说

u.get_profile().homework

you can add more errorhandling etc yourself. 您可以自己添加更多错误处理等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM