如果我将用户组关系作为ManyToMany关系,将组团关系作为ManyToMany关系,我如何将用户团队关系作为查询对象?
例如,如果我有这样的models.py:
class Group(models.Model):
name = CharField(max_length=100)
class User(models.Model):
username = models.CharField(max_length=100)
groups = models.ManyToManyField(Group, blank=True)
class Team(models.Model):
teamname = models.CharField(max_length=100)
groups = models.ManyToManyField(Group, blank=True)
我知道我可以通过创建一个类似于下面的for循环来实现它,但是如果将django的架构作为查询对象,它会更有用。
我丑陋的解决方案:
user = User.objects.get(username="Ed")
users_teams = []
user_groups = Group.objects.filter(user=user)
for group in user_groups:
group_teams = Team.objects.filter(group=group)
for team in group_teams:
user_teams.append(team)
因此,这将为我提供一个列表查询对象,我可以将其与用户关联,但它不像单个查询集一样容易使用包含每个用户 - 团队关系的查询对象。
我更喜欢看起来像这样的东西:
User.objects.get(username="Ed").groups.team_set.objects.all()
绝对不行。 有什么想法吗?
答案 0 :(得分:1)
Team.objects.filter(groups__user__username="Ed")
生成你:
SELECT
`api_team`.`id`,
`api_team`.`teamname`
FROM `api_team`
INNER JOIN `api_team_groups` ON (`api_team`.`id` = `api_team_groups`.`team_id`)
INNER JOIN `api_group` ON (`api_team_groups`.`group_id` = `api_group`.`id`)
INNER JOIN `api_user_groups` ON (`api_group`.`id` = `api_user_groups`.`group_id`)
INNER JOIN `api_user` ON (`api_user_groups`.`user_id` = `api_user`.`id`)
WHERE `api_user`.`username` = 'ed'