Search code examples
pythondjangodjango-modelsmany-to-manydjango-orm

Django: How to get all objects related to a model by another model?


I have 3 models: User, Course and Homework. Each course has some homework and some users(students). How can I have all homeworks of all courses a user is in? These are the models:

class User(AbstractUser):
    # ...

class Course(models.Model):
    students = models.ManyToManyField(User, blank=True, related_name='student_courses')
    # ...

class Homework(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='course_homeworks')
    # ...

Solution

  • Try:

    Homework.objects.filter(course__students=user)