繁体   English   中英

django-rest-framework序列化器to_representation

[英]django-rest-framework serializer to_representation

我有一个带有SerializerMethodFieldModelSerializer 我想覆盖序列化程序的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
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
    }

参考:

所以我做了以下事情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM