def build_chain(self, obj):

        chain_id = obj.id

        pokemon_objects = PokemonSpecies.objects.filter(
            evolution_chain_id=chain_id).order_by('order')
        summary_data = PokemonSpeciesSummarySerializer(
            pokemon_objects, many=True, context=self.context).data
        ref_data = PokemonSpeciesEvolutionSerializer(
            pokemon_objects, many=True, context=self.context).data

        chain = entry = OrderedDict()
        current_evolutions = None
        evolution_data = None
        previous_entry = None
        previous_species = None

        for index, species in enumerate(ref_data):

            # If evolves from something
            if species['evolves_from_species']:

                # In case this pokemon is one of multiple evolutions a pokemon can make
                if previous_species:
                    if previous_species['id'] == species['evolves_from_species']:
                        current_evolutions = previous_entry['evolves_to']

                entry = OrderedDict()

                many = False
                try:
                    evolution_object = PokemonEvolution.objects.get(evolved_species=species['id'])
                except PokemonEvolution.MultipleObjectsReturned:
                    evolution_object = PokemonEvolution.objects.filter(
                        evolved_species=species['id'])
                    many = True

                evolution_data = PokemonEvolutionSerializer(
                    evolution_object, many=many, context=self.context).data

                current_evolutions.append(entry)

            entry['is_baby'] = species['is_baby']
            entry['species'] = summary_data[index]
            entry['evolution_details'] = evolution_data or None
            entry['evolves_to'] = []

            # Keep track of previous entries for complex chaining
            previous_entry = entry
            previous_species = species

        return chain
dataset/ETHPy150Open phalt/pokeapi/pokemon_v2/serializers.py/EvolutionChainDetailSerializer.build_chain/original