首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django-rest框架序列化程序to_representation

django-rest框架序列化程序to_representation
EN

Stack Overflow用户
提问于 2015-04-21 22:45:12
回答 2查看 7K关注 0票数 7

我有一个ModelSerializer和一个SerializerMethodField。我想重写序列化程序的to_representation方法以具有自定义输出,但我不知道如何访问SerializerMethodField

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-22 02:18:09

代码语言:javascript
复制
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
    }

参考文献:

票数 9
EN

Stack Overflow用户

发布于 2015-04-23 20:12:34

所以我做了以下几件事:

代码语言:javascript
复制
def to_representation(self, instance):
        rep = super(MySerializer, self).to_representation(instance)
        duration = rep.pop('duration', '')
        return {
            # the rest
            'duration of cycle': duration,
        }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29784512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档