我正在编写一个Django查询来过滤用户所属的团队列表。 (我正在查询的团队和UserTeams模型):
class Team(models.Model)
name = models.CharField(max_length=100)
venue = models.CharField(max_length=100)
countryID = models.ForeignKey(Countries, on_delete=models.CASCADE)
owner = models.ForeignKey(User)
class UserTeams(models.Model):
userID = models.ForeignKey(User,on_delete=models.CASCADE)
teamID = models.ForeignKey(Team,on_delete=models.CASCADE)
我正在努力提出两个问题:
查询1:
第一个查询(teamquery
)通过检查owner=request.user
是否过滤了小组,然后我在模板中显示了这些小组的列表。
查询2:然后我要显示UserTeams UserID = request.user
(userteamquery
)
问题: 一些团队出现在两个查询结果中。是否存在“不平等”的情况。查询我可以使用它排除userteamquery中teamID是teamquery结果的所有UserTeams的地方吗?所以teamID = teamquery
@login_required
def teamsview(request):
teamquery = Team.objects.filter(owner=request.user)
userteamquery = UserTeams.objects.filter(userID=request.user)
return render(request, 'teammanager/teams.html', {
"teams": teamquery, "userteams": userteamquery})
试图排除()(非常确定这不是有效使用)
userteamquery =
UserTeams.objects.exclude(teamID=teamquery).filter(userID=request.user)
这在我的输出中根本没有改变任何东西
也尝试了~Q但是没有改变任何东西:
userteamquery = UserTeams.objects.filter(Q(userID=request.user),
~Q(teamID=teamquery))
*编辑 - 将__in添加到我的参数中,这可以:
userteamquery = UserTeams.objects.filter(Q(userID=request.user),
~Q(teamID__in=teamquery))