[Fixed]-How to create MyUser instance from User instance?

1👍

I think the problem is that the User can only be one or the other. A User can be a Teacher, or a Student but they cannot be both simultaneously.

I would suggest making User non abstract and work from there. Then you will just have a relationship from User to Teacher and Student which you can manipulate as you like.

0👍

Note: I’m assuming there isn’t anything unique about a teacher/student.

If the above assumption is correct, then there isn’t any reason to separate these two types of user into separate models.

All you really need to do is provide Many to many relationships for students and teachers on your course models between your User class and the course. (Since I assume a course can have multiple teachers/students and a student/teacher can teach/take multiple courses).


If they do have unique fields, then you may consider making separate UserProfile classes so a single user can have a teacher profile, and a student profile.

Based on your edit, it would appear cleaner, to me, to provide a Teacher and student profile for a user, these are essentially just separate models with a OneToOneField back to the user model.

👤Sayse

0👍

I guess your models look something like this.

class User(...):
    username = models.Charfield(unique=True, ...)

class Teacher(User, models.Model):
    teacher_field1 = models.CharField(...)

class Student(User, models.Model):
    student_field1 = models.CharField(...)

So, if you were to see the structure in the database, it’d be something like

User Table:

| id | username | ...
| 1  | teacher  | ...
| 2  | student  | ...

Teacher Table:

| user_ptr_id | teacher_field1 | ...
|     1       |   sample_text  | ...

Student Table:

| user_ptr_id | teacher_field1 | ...
|     2       |   sample_text  | ...

At the database level this structure solves your problem but at the Django ORM level, this won’t work. So, in order to have a user both as a teacher and as a student, you’d need to have a OneToOneField of the user model in both Student and Teacher model and remove the inheritance.

Leave a comment