How to set up Django models with two types of users with very different attributes

前端 未结 2 860
星月不相逢
星月不相逢 2020-12-16 05:43

Note: I\'ve since asked this question again given the updates to Django\'s user model since version 1.5.

I\'m rebuilding and making improvements to an alrea

2条回答
  •  无人及你
    2020-12-16 06:15

    I hope I understood your problem... maybe this can work? You create a abstract CommonInfo class that is inherited in into the different Sub-classes (student and businesses)

    class CommonUser(models.Model):      
        user = models.OneToOne(User)
        
    
        class Meta:
            abstract = True
    
    
    class Student(CommonUser):
        
    
    class Business(CommonUser):
        
    

    In this case the models will be created in the DB with the base class fields in each table. Thus when you are working with Students you run a

    students = Students.objects.get.all() 
    

    to get all your students including the common information.

    Then for each student you do:

    for student in students:
        print student.user.username
    

    The same goes for Business objects.

    To get the student using a user:

    student = Student.objects.get(user=id)
    

    The username will be unique thus when creating a new Student or Business it will raise an exception if an existing username is being saved.

    Forgot to add the link

提交回复
热议问题