【问题标题】:Django ManyToMany field - access fields of through table [duplicate]Django ManyToMany字段-通过表访问字段[重复]
【发布时间】:2018-06-09 21:58:09
【问题描述】:

假设我有以下模型:

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 文档中找不到示例。

【问题讨论】:

  • 我不知道这与我的问题有什么共同点。

标签: python django orm m2m


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-06-07
    • 2021-10-18
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多