0

I got Game model with 2 foreign keys away_team and home_team, both come from Club model. I got data from them rendered from the API to React.js like this:

const AllGames = () => {
    //Simplified Game object
    const [games, setGames] = useState([{
        away_score:"",
        away_team:"",
        home_score:"",
        home_team:"",
        id:''
    }]);

    //Simplified Club object
    const [clubs, setClubs] = useState([{
        name:'',
        id:""
    }])

    useEffect(() => {
        loadAllGames();
    },[])
    
    useEffect(() => {
        loadAllClubs();
    }, [games])

    const loadAllClubs = () => {
        getAllClubs()
        .then((data) => {
            setClubs(data)

        })
        .catch((error) => console.log(error))
    }


    const loadAllGames = () => {
        getAllGames()
        .then((data) => {
            setGames(data)
        })
        .catch((error) => console.log(error))
    };

With this piece of code everything is loaded smoothly, the problem is when I try to render the data:



    return (
    <Base>
        {games.map((game) => {
            return (
                <p>
                  Home) {game.home_team}: {game.home_score} Away){game.away_team}: {game.away_score}
                </p>
            )
        })}
    </Base>
  )
}
export default AllGames;

The output looks like Home) 1: 34 Away) 2: 51 It displays id of the club instead of a name. I know there was a function to switch game.home_team and game.away_team from being id's to being proper names (aka: text variables like "Team Name Example")

TLDR; I need to swap home_team or away_team in games object list into name from club objects list with matching id something like if games[1].home_team === clubs[1].id then games[1].home_team = clubs[1].name

1 Answer 1

1

You have to define a serializer method field in your django serializer. example

class GameSerializer(serializers.ModelSerializer):
    name=serializers.SerializerMethodField(read_only=True)
    
    class Meta:
        model = Property
        fields =[
            "name",
            
            #add othe game properties
        ]
        
        def get_name(self,obj):
            return obj.home_team.name
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.