简体   繁体   中英

django authentication backend

I followed the method of extending the User class for implementing custom users in my application.

As mentioned in the link, custom authentication backend needs to be written in order to return the appropriate custom user class rather than User.

However I have more than one custom users class, namely Student, Teacher,Parent.

Is there any better way than checking Student->Teacher->Parent tables to return the correct custom user?

The only solution I could think of is to actually change the User model that django uses and add a content_type field that would tell you what type of user the actual user object is. Then you could directly query on that one. You'd still need 2 queries every time to fetch the correct user object.

Alternatively you could have a model that inherits from User that encompasses all of the functionality required by your three classes, call it SuperUser for example, with a special field identifying if it is a Student, Teacher or a Parent.

Then fetch the SuperUser object for a user, thus containing all of the required data. By using the special field identifying which user type they are, you could have a proxy model that you have for each type of user (ProxyStudent, ProxyTeacher, etc) that would make it behave as it should.

This would mean you only ever have 2 database hits regardless, but you get to store the data as specified as long as you use the proxy model to access them.

class SuperUser(User):
  type = models.IntegerField(choices=[(0, 'Student'), (1, 'Teacher'), (2, 'Parent')]
  # insert all the data for all 3 seperate classes here

class ProxyStudent(SuperUser):
  class Meta:
    proxy = True

  def special_student_method(self):
    pass


fetch request.user
and make request.user an instance of SuperUser


student = ProxyStudent()
student.__dict__ = request.user.__dict__

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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