django-rest-framework序列化器to_representation

nor*_*tpy 5 django python-2.7 django-rest-framework

我有ModelSerializer一个SerializerMethodField.我想覆盖to_representation序列化程序的方法以获得自定义输出,但我不知道如何访问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
Run Code Online (Sandbox Code Playgroud)

moz*_*azg 7

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
    }
Run Code Online (Sandbox Code Playgroud)

参考: