matiit
matiit

Reputation: 8017

Django, need some specified groups of users

I need let's say Instructors, Students and so on. Both groups are users, could login etc. But for example Instructor need many to many relationship with model Subjects. How to achieve that?

Upvotes: 0

Views: 148

Answers (3)

Jordan Reiter
Jordan Reiter

Reputation: 21002

I wouldn't use inheritors here. Just create models that point to User:

class Instructor(models.Model):
    user = models.OneToOneField(User)
    # other fields
    subjects = models.ManyToManyField('Subject')

class Student(models.Model):
    # other fields
    user = models.OneToOneField(User)

class Subject(models.Model):
    name = models.CharField(max_length=40)

This has the benefit of keeping the common user functionality separate from the Instructor and Student functions. There's really no reason to actually treat Instructors or Students as Users.

Upvotes: 1

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16356

You can't point Subject to User-who-is-Instructor model, it can't be expresed in SQL.

What you can do is e.g. to point Subject to User model, making sure in your code that you only create Subject instances for User-s that are members of Instructors group.

Upvotes: 0

Andrew Sledge
Andrew Sledge

Reputation: 10351

Create a class Instructors that would inherit from Users. Within this class provide the many-to-many relationship. You could also use the profile module to identify the separation.

There are good examples of both here.

EDIT: There is also a good post by James Bennett here.

Upvotes: 1

Related Questions