Django-rest-framework serializer to_representation

I have ModelSerializer

c SerializerMethodField

. I want to override the to_representation

serializer method to have custom output, but I don't know how to access 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

      

+3


source to share


2 answers


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
    }

      

link



+5


source


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,
        }

      

+1


source







All Articles