'If I have a marhsmallow schema with many = True, that has a nested schema, how can i access the parent's ID from the nested schema?

If I have a marhsmallow schema with many = True, that has a nested schema, how can i access the parent's ID from the nested schema?

I tried something like this...

class PlayerSchema(Schema):
    id = fields.Int()
    name = fields.Str()
    games_played = fields.Method("get_game_count")
    
    def get_game_count(self,o):
        """business logic here, but something like the following"""
        
        return Game.objects.filter(tournament_id=self.context['tournament_id'],player=o.id).count()

class GameSchema(Schema):
    id = fields.Int(dump_only=True)
    tournament_id=fields.Int()
    player1 = fields.Nested(PlayerSchema, dump_only=True)
    player2 = fields.Nested(PlayerSchema, dump_only=True)
    player1_score = fields.Int(dump_only=True)
    player2_score = fields.Int(dump_only=True)

    @pre_dump()
    def set_context(self, parent, **kwargs):
        self.context["tournament_id"] = parent.tournament_id
        return parent

In my actual use case there are a lot more things going on with the business logic, so don't get too lost in how this data appears to be organized... the specific problem i'm trying to solve is that I can't reliably access the "Game ID" from the method on the nested PlayerSchema.

When I tried this with something like

games_data = GameSchema(many=True).dump(data)

There is only a single context for all the "many" GameSchema(s) , not for each individual object, so the code above only really has the context for the last "GameSchema"

Does anyone have any idea how I can reliably access that "game_id" from the nested schema?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source