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

1k views Asked by At

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:

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 (e.g Teachers)? Can AUTH_USER_MODEL except a dictionary to be able to distinguish between two types of users? 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

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.

1

There are 1 answers

3
jpwagner On BEST ANSWER

Keep authentication through 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:

    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 uyou can say

u.get_profile().homework

you can add more errorhandling etc yourself.