Django ManyToMany 字段 - 通过 table 访问字段

Django ManyToMany field - access fields of through table

假设我有以下模型:

class User(Model):
    username = CharField(...)

class Project(Model):
    project_name = CharField(...)
    workers = ManyToManyField(User, through="ProjectAssignment")

class ProjectAssignment(Model):
    user = ForeignKey(User)
    project = ForeignKey(Project)
    role = CharField(...)  # name of the role a user has on a project

如何进行查询以获取在名为 XY 的项目中具有角色 Developer 的用户?我在 Django 文档中找不到示例。

您应该通过直通模型本身进行查询。

developers = User.objects.filter(projectassignment__role='Developer', projectassignment__project=my_project)