简体   繁体   中英

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

尝试:

Homework.objects.filter(course__students=user)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM