Reputation: 69
So I am trying to create the following type of relationship:
Teacher has many students, Student has many Teachers, Student has many(2) Parents, Parent has many Students.
The thing that confuses me is that I am trying to archive that with the extenesion of the AbstractUser. I totally confused myself over how I would create the models. Currently I have this:
class User(AbstractUser):
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
is_parent = models.BooleanField(default=False)
class Student(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
parent = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='parents'
)
class Parent(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
student = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='students'
)
class Teacher(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
student = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='students'
)
Upvotes: 0
Views: 45
Reputation: 599600
I think you're overcomplicating things here. I don't see the need for all those models and one-to-one relations. Why not a simple User model with all the relations?
class User(AbstractUser):
students = models.ManyToManyField('self', related_name='teachers', symmetrical=False)
children = models.ManyToManyField('self', related_name='parents', symmetrical=False)
Note, the related name is for the reverse relationship; if you are one of my students, I am your teacher. You don't need separate fields for those. You do need to set symmetrical to False - otherwise Django would assume if you are one of my students, I am one of your students, which is obviously not right.
Upvotes: 4