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

前端 未结 2 855
星月不相逢
星月不相逢 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:11

    This is not a complete solution, but it will give you an idea of where to start.

    • Create a UserProfile model in mainsite. This will hold any common attributes for both types of users. Relate it to the User model with a OneToOne(...) field.
    • Create two more models in each app, (student/business), Business and Student, which have OneToOne relationships each with UserProfile (or inherit from UserProfile). This will hold attributes specific to that type of users. Docs: Multitable inheritance / OneToOne Relationships
    • You may add a field in UserProfile to distinguish whether it is a business or student's profile.

    Then, for content management:

    • Define the save() functions to automatically check for conflicts (e.g. There is an entry for both Business and Student associated with a UserProfile, or no entries).
    • Define the __unicode__() representations where necessary.
    0 讨论(0)
  • 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)
        <any other common fields>
    
        class Meta:
            abstract = True
    
    
    class Student(CommonUser):
        <whatever>
    
    class Business(CommonUser):
        <whatever>
    

    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

    0 讨论(0)
提交回复
热议问题