Search code examples
pythondjangodictionarydjango-serializer

Django Serializer How to loop over dictionary value and return in serializer


I have following dictionary inside list

self.passengers = [{'first_name':'Harry','last_name':'kane'},{'first_name':'cristiano','last_name':'aviero'}

I Have set my serializer as following

class PassengerSerializer(serializers.Serializer):
    first_name = serializers.CharField()
    last_name = serializers.CharField()


class TicketDetailSerializer(serializers.Serializer):
    passenger = PassengerDetailSerializer(many=True)

I have set my code as following to extract passenger data

'passenger': [{
               'last_name': [passenger['last_name'] for passenger in self.passengers],
                'first_name': [passenger['first_name'] for passenger in self.passengers]
                }],

But I am only getting firstname ->'harry' and lastname-> kane what shall I do next to get all dictionary of first name and last name is self.passengers? I am getting output as:

"passenger": [
        {
            "lastname": "['kane', 'aviero']",
            "firstname": "['harry', 'cristiano']"
        }
    ]

I want output as

"passenger": [
            {
                "lastname": "kane",
                "firstname": "harry"
            },
            {
                "lastname": "aviero",
                "firstname": "cristiano"
            }
        ]

Solution

  • 'passenger': [{
                   'last_name': passenger['last_name'],
                    'first_name': passenger['first_name']
                  } for passenger in self.passengers ]