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" }
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')
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With