Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST -- How to "modify" value before returning the REST response?

I have done some research, but I'm not quite sure what I'm technically looking for so I didn't find much information. I am using Django REST.

model

class Car(models.Model)
    name =  name = models.CharField(blank=True, null=True, db_index=True)
    speed = models.IntegerField(default=SPEED.FAST)

view

class CarViewSet(viewsets.ModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarSerializer

serializer

class CarSerializer(serializers.ModelSerializer):
    class Meta:
        model = Car

Question: My speed field in Car model is an integer, when I access the REST endpoint API, I don't want to return an integer, but instead a string. Basically:

if speed is 0:
    return "slow"
else:
    return "fast" 

So an example JSON response is:

{ name: "ferrari", speed: "fast" }
like image 740
Rich Episcopo Avatar asked Nov 10 '15 22:11

Rich Episcopo


Video Answer


2 Answers

You can use SerializerMethodField:

class CarSerializer(serializers.ModelSerializer):

    speed = serializers.SerializerMethodField()

    def get_speed(self, obj):
        if obj.speed == 0:
            return "slow"
        else:
            return "fast"

    class Meta:
        model = Car
        fields = ('name', 'speed')
like image 63
Gocht Avatar answered Oct 02 '22 20:10

Gocht


Adding another approach -

class CarSerializer(serializers.ModelSerializer):

    class Meta:
        model = Car
        fields = ('name', 'speed')

    def to_representation(self, data):
        data = super(CarSerializer, self).to_representation(data)
        data['speed'] = 'slow' if data.get('speed') == 0 else 'fast'
        return data

Also, one improvement in @Gocht answer. Better practice to omit extra else statement while using conditional return in method get_speed -

def get_speed(self, obj):
    if obj.speed == 0:
        return "slow"
    return "fast"
like image 33
Anshul Tiwari Avatar answered Oct 02 '22 20:10

Anshul Tiwari