如何从多对多关系中检索条目

How to retrieve entries from a many-to-many relationship

我有一个应用程序,用于管理助理工作。因此,该模型由 3 个模型组成:Person、Course、Application(典型的多对多关系)。 我的 models.py 看起来如下:

class Person(AbstractUser):
  ...

class Course(models.Model):
  year = models.charField(max_length=9)
  term = ...

class Applications(models.Model):
    applicant = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="applicant")
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    status = models.CharField(max_length=255, default='Pending')

在表单的上下文中,我需要检索一个人已被雇用的所有课程以填充下拉列表。

很容易得到当前登录用户状态为'Hired':

的所有应用
Applications.objects.filter(applicant=user, status="Hired")

但我无法获得所有相关课程的查询集:

Applications.objects.filter(applicant=user, status="Hired").course_set

returns 我一个:

AttributeError: 'QuerySet' object has no attribute 'course_set'

根据Django documentation,该属性应该存在。

我做错了什么?

反向访问器 course_set 可用于 Applications 模型的 实例 ,而不是查询集(Applications.objects.filter returns).

例如,如果您有一个名为 applicationApplications 实例,您可以这样做:

application.course_set.all()

获取 Courseapplication 相关的所有实例。


如果您想从过滤后的 Applicaitons 中获取相关的 Course 个实例:

Applications.objects.filter(
    applicant=user, status="Hired"
).values_list(
    'course', flat=True
).distinct()

这将 return 相关 Course 个实例的主键。

只需使用_set 即可访问它。

首先尝试使用文档,了解思路。 https://docs.djangoproject.com/en/3.0/ref/models/relations/