Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Django REST Framework Make the REST Framework Work for You Control the QuerySet

Y B
Y B
14,136 Points

Django rest framework, override get queryset

I think this looks ok, but I can't seem to pass the challenge for some reason?

scorekeeper/views.py
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView

from . import models
from . import serializers


class GameListCreate(generics.ListCreateAPIView):
    queryset = models.Game.objects.all()
    serializer_class = serializers.GameSerializer


class GameScoresList(generics.ListAPIView):
    queryset = models.Score.objects.all()
    serializer_class = serializers.ScoreSerializer

    def get_queryset(self, game_pk):
        return self.queryset.filter(id=self.kwargs.get('game_pk'))

4 Answers

Tatiana Vasilevskaya
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tatiana Vasilevskaya
Python Web Development Techdegree Graduate 28,599 Points

There are two issues here. The first one is that get_queryset method doesn't accept game_pk argument.

The second thing is the queryset filtering. The get_queryset method has to filter the queryset to only have scores for the game with the specific pk. The current implementation:

def get_queryset(self, game_pk):
        return models.Score.objects.filter(id=self.kwargs.get('game_pk'))

i.e. you filter by the score id, but you have to filter by game.

Bas Kuunk
Bas Kuunk
21,308 Points

According to your comment, this should work:

def get_queryset(self):
        return models.Score.objects.filter(game_id=self.kwargs.get('game_pk'))

But it does not. Neither does my code:

def get_queryset(self):
        return self.queryset.filter(game_id=self.kwargs.get('game_pk'))

Can anyone tell me what is wrong with either of these?

Anders Prytz
Anders Prytz
26,193 Points

Hi Aurélien!

You would have to use 'game' and not 'game_id' (found out after some attempts). Such that your filter would look like: game=self.kwargs.get('game_pk')

Otherwise it looks correct:)

This should be marked as the answer.

I tried this too:

    def get_queryset(self):
        return self.queryset.filter(game_id=self.kwargs.get('game_pk'))

Can anyone tells me what is wrong there?

thanks Anders