Mehdi Sadour
Mehdi Sadour

Reputation: 1

Custome the display's field in django REST

I use Django REST and I would know if it is possible to customise the display of attributes in the json response.

Exemple :

class MyModel(models.Model):
    name = models.CharField(max_length=300)

and my serializer :

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['name']

But instead to see {'name' : 'its value'}, I would see {'My customed model name' : 'its value'}.

Do you think that it's possible?

Thank you very much.

Upvotes: 0

Views: 345

Answers (3)

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

You can do this in this way

class MyModelSerializer(serializers.ModelSerializer):
    other_name = serializers.CharField(source='name')
    class Meta:
        model = MyModel
        fields = ['other_name']

Upvotes: 0

Shinra tensei
Shinra tensei

Reputation: 1293

One way you could do it is using a SerializerMethodField (https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield)

class MyModelSerializer(serializers.ModelSerializer):

    my_customed_model_name = serializers.SerializerMethodField()

    def get_my_customed_model_name(self, obj):
        return obj.name

    class Meta:
        model = MyModel

Although if you want the field name to have spaces in it, this solution won't work for you.

Upvotes: 0

p14z
p14z

Reputation: 1810

You can override the to_representation method of the serializer to change the name of the field:

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['name']

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        # ret is an OrderedDict, so this will change the order of the result.
        ret['custom_name'] = ret.pop('name')
        return ret

    def to_internal_value(self, data):
        # if you want to write to the serializer using your custom name.
        data['name'] = data.pop('custom_name')
        return super().to_internal_value(data)

Upvotes: 1

Related Questions