horse
horse

Reputation: 501

How To Access Many Field In One-To-Many Relationship

I have two different user types, Teachers and Students. My students have a one-to-many relationship with a Teacher (a student can have one teacher / a teacher can have many students). I am able to access a student's Teacher in templates like this user.student.teacher, but I dont know how to access a list of a Teacher's Students?

# override default User model
class User(AbstractUser):
    user_type = models.CharField(choices=USER_TYPES, max_length=255, default='student')

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, default=None, null=True)

Thank you.

Upvotes: 0

Views: 48

Answers (2)

Hisham___Pak
Hisham___Pak

Reputation: 1490

Django automatically allows you to access other way and by default names manager student_set. Note, model name followed by _set. You can override this name by setting related_name in ForeignKey.

Learn in depth here

  • You can query, teacher.student_set.all() this will show teacher's all students.

  • You can also use related_name like this,

class Student(models.Model):
    ...
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, default=None, null=True, related_name='students')

and then query like this, teacher.students.all()

Upvotes: 1

JPG
JPG

Reputation: 88689

Simply

user.teacher.student_set.all()

Reference:

Upvotes: 1

Related Questions