Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest-framework serializer to_representation

I have a ModelSerializer with a SerializerMethodField. 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:

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
like image 612
Sam R. Avatar asked Apr 21 '15 22:04

Sam R.


2 Answers

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,
        }
like image 23
Sam R. Avatar answered Sep 18 '22 13:09

Sam R.


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:

  • https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L417
like image 156
mozillazg Avatar answered Sep 20 '22 13:09

mozillazg