#DRF Different Field Name Serialization

5 messages · Page 1 of 1 (latest)

olive shoal
#

Hi , I need a best practice.

I will add new data to my SampleModel with sending a request to external API. But on external api response, field names different from my model fields. So I want to serialize this data to my SampleModel object.

class SampleModel(models.Model):
    sample_name = models.Charfield()
    sample_age = models.IntegerField()

external_api_response = {
  "sampleName":"foo",
  "sampleAge":"bar"
}

I want this external_api_response to serialize to my model. But when i create a ModelSerializer fields not match. What is the best practice for this case.

forest aspen
#

For read-only serializers, you could define field lookups/aliases e.g. using my_field = serializers.CharField(source="myField"). I don't think that works for a writable serializers though (but I haven't tried).

The simplest solution may preparing a correct payload for the serializer itself by renaming dict keys yourself before.

olive shoal
#

Thanks for reply,

When I make it readonly fields, I cant get data from validated_data

I tried to override to_internal_value like

class SampleModelSerializer(models.ModelSerializer):
    
    def to_internal_value(self, data):
        data['sample_name'] = data['sampleName']
        data['sample_age'] = data['sampleAge']
        return data

    class Meta:
        model = SampleModel
        fields = '__all__'

is it good way to do it ?

forest aspen
#

I guess that can work

#

```py

code

```

for colors, btw