App has Game model and Player model.
I want to get a list of the Game objects in which the logged in user has a Player. This is to show that user’s Game history in a dashboard so they can see past games.
This code gets all the Game objects. So it shows the history of every user.
class DashboardListView(generic.ListView):
model = Game
template_name = 'dashboard.html'
context_object_name = 'tournament_list'
def get_queryset(self):
return Game.objects.filter()
I can narrow down to completed games for every player like this:
class DashboardListView(generic.ListView):
model = Game
template_name = 'dashboard.html'
context_object_name = 'tournament_list'
def get_queryset(self):
return Game.objects.filter(completed=True)
I tried this to get to narrow down to only games of the specific user:
def get_queryset(self):
if Player.objects.filter(owner=self.request.user).exists():
mine = Player.objects.filter(owner=self.request.user).get()
return Game.objects.filter(
Q(player1=mine) | Q(player2=mine) | Q(player3=mine) & Q(completed=True))
But because there are multiple Player objects it throws this error:
get() returned more than one Player -- it returned 12!
What I want are the 12 Games in which the user has those 12 Player objects.
How can I get those Game objects in which the user has a Player object?
1