Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Using views to change DRF response

I would like to alter the response from an API.

However, it does not alter the result properly. I get a KeyError: 'game'.

I am not sure why, as my API response (via URL) seems to have the value game in it. I may be getting confused with the JSON response, and the python object.

I have a sample of the API response below

results from API

{
    "pk": 995,
    "game": [
        {
            "name": "Finance",
            "gamelevel": 3
        },
        {
            "name": "Data",
            "gamelevel": 1
        }
    ]
},

views.py

class TagList(viewsets.ModelViewSet):
    queryset = Task.objects.filter(game__isnull=False).all()
    serializer_class = TagSortSerializer

    def get_queryset(self):
    test = self.queryset.values('title', 'game__name')
    result = defaultdict(set)
    for item in queryset:
        parent   = {'name': 'NoLevel_1'}
        children = []
        for game in item['game']:
            if game['gamelevel'] == 1:
                parent = game
            else:
                children.append((game['gamelevel'], game['name']))
        result[parent['name']].update(children)

    result = [ 
        {
            'name': parent, 
            'game_child': [
                {'name': name, 'gamelevel': gamelevel} for gamelevel, name in games
            ],
            'gamelevel': 1, 
        } for parent, games in result.items()
    ]

    return result
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You're using the values queryset method to get only a selection of fields from the model, and the only fields you've specified are title and tag__name. So you won't get game or any of the other keys you've used.

You certainly don't want to use values here in the first place; just do a normal query and access fields via dot lookup rather than dictionary.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!