Django ManyToMany字段 - 访问通过表的字段

时间:2017-12-29 12:54:56

标签: python django orm m2m

说我有以下型号:

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

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

1 个答案:

答案 0 :(得分:1)

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

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