Sam R.
Sam R.

Reputation: 16450

django-rest-framework serializer to_representation

I have a ModelSerializer with a SerializerMethodField. I want to override the to_representation method of the serializer to have custom output but I don't know how to access the SerializerMethodField:

class MySerializer(serializers.ModelSerializer):

    duration = serializers.SerializerMethodField()

    def get_duration(self, obj):
        return obj.time * 1000

    def to_representation(self, instance):
        return {
            'name': instance.name, 
            'duration of cycle': # HOW TO ACCESS DURATION????
        }


    class Meta:
        model = MyModel

Upvotes: 7

Views: 7503

Answers (2)

Sam R.
Sam R.

Reputation: 16450

So I did the following:

def to_representation(self, instance):
        rep = super(MySerializer, self).to_representation(instance)
        duration = rep.pop('duration', '')
        return {
            # the rest
            'duration of cycle': duration,
        }

Upvotes: 4

mozillazg
mozillazg

Reputation: 720

def to_representation(self, instance):
    duration = self.fields['duration']
    duration_value = duration.to_representation(
        duration.get_attribute(instance)
    )
    return {
        'name': instance.name,
        'duration of cycle': duration_value
    }

ref:

Upvotes: 9

Related Questions