简体   繁体   English

Django:如何通过另一个模型获取与模型相关的所有对象?

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

I have 3 models: User , Course and Homework .我有 3 个模型: UserCourseHomework 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如果你有用户 ID,你可以这样做

Homework.objects.filter(course__student_courses__id=user_id)

i used student_courses in the above code because you set the related_name我在上面的代码中使用了student_courses因为你设置了related_name

you could also do this if you have multiple user or user id如果您有多个用户或用户 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因此,您可以使用任何用户字段进行过滤,只需将course__student_courses__id替换为course__student_courses__field_name

One last thing you can also us startswith, exact, iexact, ... like course__student_courses__field_name__startswith最后一件事你也可以让我们startswith, exact, iexact, ...就像course__student_courses__field_name__startswith

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取所有相关的 Django 模型对象 - Get all related Django model objects 如何在Django模型ForeignKey和OneToOneField中获取所有相关对象 - How to get all related objects in django model ForeignKey and OneToOneField Django过滤与另一个模型相关的模型对象 - Django filter model objects related to another model 在Django中,如何获取一个模型的所有实例,而与fk的第一个模型相关的另一个模型的实例不存在? - In Django, how to get all instances of a model where an instance of another model related to the first by fk does not exist? 在不知道Django中模型名称的情况下获取所有相关对象 - Get all related objects without knowing model name in Django Django通过“通过”关系表从模型中获取所有相关对象 - Django get all related objects from model with 'through' relationship tables Django:获取所有对象和相关模型的第一条记录 - Django: Get all objects and the first record of a related model 如何获取查询集中每个 object 的所有相关对象,由 Sqlalchemy 中的另一个 model 过滤? - How to get all related objects of every object in a queryset, filtered by another model in Sqlalchemy? 如何通过发送与模型相关的 objects.all() 获取外键 - How to get the foreignkey with sending objects.all() related to the Model 通过 model 获取所有带有过滤器的相关对象 - Get all related objects with filter on through model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM