Skip to content Skip to sidebar Skip to footer

How To Set Up Django Models With Two Types Of Users With Very Different Attributes

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 already existing Django site and

Solution 1:

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.

Solution 2:

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)

classCommonUser(models.Model):      
    user = models.OneToOne(User)
    <any other common fields>

    classMeta:
        abstract = True


classStudent(CommonUser):
    <whatever>

classBusiness(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

Post a Comment for "How To Set Up Django Models With Two Types Of Users With Very Different Attributes"