ParsaAi
ParsaAi

Reputation: 349

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

Upvotes: 0

Views: 2429

Answers (2)

Chapi Menge
Chapi Menge

Reputation: 136

If you have user object you could do like

Homework.objects.filter(course__students=user)

if you have user id you could do like

Homework.objects.filter(course__student_courses__id=user_id)

i used student_courses in the above code because you set the related_name

you could also do this if you have multiple user or user id

Homework.objects.filter(course__student_courses__in=user_ids) # user_ids = [1,3,4]

So you can use any of the user fields to filter to by just replacing course__student_courses__id with course__student_courses__field_name

One last thing you can also us startswith, exact, iexact, ... like course__student_courses__field_name__startswith

Upvotes: 1

Bartosz Stasiak
Bartosz Stasiak

Reputation: 1632

Try:

Homework.objects.filter(course__students=user)

Upvotes: 1

Related Questions