I'm using django to build a website and I want to link tutors and students

I'm currently stuck with the best way of assigning tutors to students and then tutors can add lessons for these students and they can both see these lessons, but you can only assign one foreign key to the class "MyLessons". So I'm not sure whether it's worth creating a MyStudents class, storing students inside this (but their user is the same as tutors except is_tutor=false) and then for each student creating a MyLessons class that the tutor can add to.

I think I can make an approach I'm just worried it won't be very efficient or there will be some serious problems later on. Such as the other way was that each lesson would auto take in the tutors email (I set the username to email) and then when displaying the tutors lessons it would go through every lesson and display the lessons with a matching email... problems are though, if I reassign a student to a new tutor I'd like the new tutor to see the lessons but this would mean manually changing each and if there are too many lessons and students the process would get slow.

A Tutor has many students. A student potentially has more than one tutor. So at first glance that's a ManyToMany relational field.

One thing that's at first confusing is that the relationship is symmetric, but is defined on one object and only implicitly on the other. But the implicit and explicit fields both work the same, for manipulating a set of relationships.

class Tutor( models.Model)
    students = ManyToManyField( Student, related_name='tutors', ...)


student_instance.tutors.add( tutor_instance)
tutor_instance.students.add( student_instance)

both accomplish the same. (In the simplest case. Read the doc for the exceptions).

It may or may not help to know that behind the scenes, Django is manipulating an implicit table whose objects have two fields, a ForeignKey to a student and a ForeignKey to a tutor. It can sometimes be useful to make this table explicit, so you can attach extra information to the relationship such as date created, who created it, etc. Look up the "through" option of ManyToMany if you want to do this.

Further examples here.

Back to Top