Home > Software design >  Django: normalize/modify a field in model serializer
Django: normalize/modify a field in model serializer

Time:11-07

I have a model serializer like this:

class FoooSerializers(serializers.ModelSerializer):
    class Meta:
        model = Food
        fields = [
            'id',
            'price',]

Here I have the price with trailing zeros like this: 50.000 and I want to .normalize() to remove the trailing zeros from it. Is this possible to do that in this serializer?

CodePudding user response:

class FoooSerializers(serializers.ModelSerializer):
  class Meta:
    model = Food
    fields = ['id','price',]
def to_representation(self, instance):
    representation = super().to_representation(instance)
    representation['price'] = int(price)
    return representation
  • Related