Home > front end >  Django: How to get all objects related to a model by another model?
Django: How to get all objects related to a model by another model?

Time:07-11

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')
    # ...

CodePudding user response:

Try:

Homework.objects.filter(course__students=user)
  • Related