I am writing a Django query to filter a list of teams which the user is a part of. (The Team and UserTeams models I am querying):
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)
I'm struggling to make two queries:
Query 1:
The first query (teamquery
) filters the Teams by checking if the owner=request.user
, and I then display a list of these teams in my template.
Query 2: I then want to display a list of teams where the UserTeams UserID = request.user
(userteamquery
)
Problem: Some teams are appearing in both query results. Is there a 'not equal' query I can use where it will exclude all UserTeams in the userteamquery where the teamID is a result of teamquery? so 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})
Tried to exclude() (pretty sure this isn't even valid use)
userteamquery =
UserTeams.objects.exclude(teamID=teamquery).filter(userID=request.user)
This didnt change anything at all in my output
Also tried ~Q but didnt change anything either:
userteamquery = UserTeams.objects.filter(Q(userID=request.user),
~Q(teamID=teamquery))
*Edit - Added __in to my parameter, this works:
userteamquery = UserTeams.objects.filter(Q(userID=request.user),
~Q(teamID__in=teamquery))