Multy查询集。比较两个查询集并找到比较的项目

时间:2019-06-11 13:01:11

标签: django django-queryset

我有一个不清楚的任务。我需要找到一个存在于两个用户中的对象。 例如。每个用户都有AdditionalInfo,我还有表AddInfoTeam,其中我有ManyToMany关系:

class AddInfoTeam(models.Model):
    add_info = models.ForeignKey(AdditionalInfo,
                                 on_delete=models.CASCADE)
    team = models.ForeignKey(Team,
                             on_delete=models.CASCADE)

每个用户可以存在许多团队中。

例如,我有2个用户-user1和user2。我需要找出他们在一起的团队。

这是我的示例代码:

# get additional info for user1
add_info_dealer = AdditionalInfo.objects.get(user=dealer)
# get additional info for user2
 add_info_grower = AdditionalInfo.objects.get(user=grower)

# get all teams for user 1
 dealer_teams = AddInfoTeam.objects.filter(add_info=add_info_dealer)
# # get all teams for user 2
    grower_teams = AddInfoTeam.objects.filter(add_info=add_info_grower)

# this is bad code, i try to find someting better than this:

    for dealer_team in dealer_teams:
        for grower_team in grower_teams:
            if grower_team.id == dealer_team.id:
                return grower_team

1 个答案:

答案 0 :(得分:0)

您可以找到两个查询。与您的实现类似。

add_info_dealer = AdditionalInfo.objects.get(user=dealer)
add_info_grower = AdditionalInfo.objects.get(user=grower)
dealer_teams = AddInfoTeam.objects.filter(add_info=add_info_dealer)
grower_teams = AddInfoTeam.objects.filter(add_info=add_info_grower)
return dealer_teams.intersection(grower_teams)