Search code examples
pythondjangodjango-modelsdjango-users

How can I relate some, but not all, models to users using Django?


I have a project which includes two different apps: users and school. In my current implementation, the users app contains a custom user class derived from Djagno's AbstractUser. It defines allowed user types as student or teacher, and the user must select one during registration. The school app contains a classroom model which I need to relate to students and one or more teachers.

I have two main problems here. The first is regarding how to relate the classroom model to only specific users restricting their access based on their user type. I have tried using a ManyToManyField relation in the classroom model in order to associate the instance with the user who created it (and then I would later allow the user to add students). It appears I don't understand this field correctly -- it actually all users to all classroom instances. This obviously does not meet my requirement to restrict access among different classroom instances.

OneToOneField and ForeignKey do not seem to meet my needs either. I have tried adding those fields to my user, but then I am restricted to a single classroom per user which is not acceptable either.

I have also played around with creating groups named something like "Classroom_A_teachers" and "Classroom_A_students" and then assigning permissions to them. This approach seems more complicated than necessary.

Am I overlooking something here? This is my first Django project, and I could easily have missed something basic.

Problem two is regarding adding a teacher and student model. I would like to allow a user who is registered as a teacher to be able to create a classroom instance and then to populate that classroom with student instances. Students could optionally create an account too. They would receive a classroom ID from their teacher, enter it, and their account would then be linked to the classroom instance. How can I then associate this user with an existing student model? I have toyed around with this concept with no success.

Any insight is greatly appreciated!


Solution

  • It appears I don't understand this field correctly -- it actually all users to all classroom instances.

    It shouldn’t do that. It can just look that way in the Django Admin. The only ones actually in the ManyToMany field are the ones which are highlighted/greyed.

    ManyToMany is appropriate for your use case.