简体   繁体   English

django-rest-framework序列化器to_representation

[英]django-rest-framework serializer to_representation

I have a ModelSerializer with a SerializerMethodField . 我有一个带有SerializerMethodFieldModelSerializer 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 : 我想覆盖序列化程序的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
    }

ref: 参考:

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

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

相关问题 在django-rest-framework中使用.to_representation()和.to_internal_value? - Usage of .to_representation() and .to_internal_value in django-rest-framework? Rest 框架序列化程序的架构,修改了 to_representation - Schema for Rest Framework serializer with modified to_representation 必须实现 Django rest 框架 to_representation - Django rest framework to_representation must be implemented Django Rest Framework 3.0 to_representation未实现 - Django Rest Framework 3.0 to_representation not implemented 如果值为空,则自定义 Django Rest Framework Serializer 字段不运行 `to_representation()` - Custom Django Rest Framework Serializer Field not running `to_representation()` if value is null 使用to_internal_value()和to_representation()的Django Rest Framework读写平面序列化器 - Django Rest Framework read-write flat serializer using to_internal_value() and to_representation() Django REST to_representation:序列化器字段最后出现 - Django REST to_representation: Have serializer fields appear last Django Rest Framework中的to_representation()能否访问正常字段 - Can to_representation() in Django Rest Framework access the normal fields Django Rest 框架在带有源的foreignKey上有一个to_representation - Django Rest Framework have a to_representation on a foreignKey with source django-rest-framework 中的可写嵌套序列化程序? - Writable nested serializer in django-rest-framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM