【问题标题】:django-rest-framework serializer to_representationdjango-rest-framework 序列化器 to_representation
【发布时间】:2015-06-29 08:10:19
【问题描述】:

我有一个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

【问题讨论】:

    标签: django python-2.7 django-rest-framework


    【解决方案1】:
    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
        }
    

    参考:

    【讨论】:

      【解决方案2】:

      所以我做了以下事情:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 2015-10-14
        • 1970-01-01
        • 2016-03-15
        • 2018-06-23
        • 2016-09-29
        相关资源
        最近更新 更多