Django serializer to convert list of dictionary keys to model fields

I am using pandas openpyxl to read excel file in my project. After reading the excel file I end up with list of dictionaries. These dictionaries have keys such as "Year 2024", "Range", "Main Point", and etc.

I have a field in my Django app that has these fields such as "year", "range", "main_point".

My question is how can I write a serializer to convert dictionary keys to fields in my model? I want to do this in serializer because I also want to validate dictionary data.

So I have this list:

my_data = [
{"Year 2024": "5", "Range":"2", "Main Point": "OK"},
{"Year 2024": "6", "Range":"3", "Main Point": "OK"},
{"Year 2024": "7", "Range":"4", "Main Point": "OK"},
...
]

and my model

class MyModel(models.Model):
    year = models.IntegerField(...)
    range = models.IntegerField(...)
    main_pont = models.CharField(...)

Thanks

Try:

from rest_framework import serializers
from .models import MyModel

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['year', 'range', 'main_point']

    def to_internal_value(self, data):
        mapped_data = {
            'year': data.get('Year 2024'),
            'range': data.get('Range'),
            'main_point': data.get('Main Point')
        }
        return super().to_internal_value(mapped_data)

    def validate_year(self, value):
        try:
            return int(value)
        except ValueError:
            raise serializers.ValidationError("Year must be a valid integer.")

    def validate_range(self, value):
        try:
            return int(value)
        except ValueError:
            raise serializers.ValidationError("Range must be a valid integer.")

    def validate_main_point(self, value):
        if not isinstance(value, str):
            raise serializers.ValidationError("Main point must be a valid string.")
        return value

So, as an example of usage:

my_data = [
    {"Year 2024": "2023", "Range": "2", "Main Point": "OK"},
    {"Year 2024": "2025", "Range": "3", "Main Point": "OK"},
    {"Year 2024": "2022", "Range": "4", "Main Point": "OK"}
]

serializer = MyModelSerializer(data=my_data, many=True)

if serializer.is_valid():
    serializer.save()
else:
    print(serializer.errors)
Back to Top