我有一个名为Project
的{{1}},User
和多对多通过表:
ProjectMembership
现在我想要一个特定用户所在的所有活动项目的所有活动项目经理的列表。我在下面使用了以下查询和循环,但也许有一种方法可以在没有循环的情况下执行此操作?
class Project(models.Model):
'''Project model
'''
name = models.CharField(max_length=255, unique=True)
users = models.ManyToManyField(
settings.AUTH_USER_MODEL,
through='ProjectMembership'
)
is_active = models.BooleanField(
default=True,
)
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, null=True)
is_active = models.BooleanField(
default=True,
)
projects = models.ManyToManyField(
Project,
through=ProjectMembership
)
class ProjectMembership(models.Model):
'''Project Membership model
'''
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT
)
project = models.ForeignKey(Project, on_delete=models.PROTECT)
is_project_manager = models.BooleanField(default=False)
答案 0 :(得分:1)
你可以这样试试,
memberships = ProjectMembership.objects.filter(
user__is_active=True, is_project_manager=True,
project__is_active=True
)
users = [membership.user for membership in memberships]