whoisearth
whoisearth

Reputation: 4170

serializer set custom values

I have a model serializer that is like so -

class VariableSerializer(serializers.ModelSerializer):
    owner_name = serializers.Field(source='owner_id.owner_name')

    class Meta:
        model = Varmst
        resource_name = 'varmst'
        fields = ('varmst_id', 'varmst_type', 'varmst_name', 'varmst_value',
            'varmst_desc')

'varmst_value' corresponds to an integer that, depending on that integer can mean a different thing. How do I return the normalized value OVER the integer?

ie. if 'varmst_value' = 2 then I want the serializer to return 'varmst_type': 'email' if 'varmst_value' = 3 then I want the serializer to return 'varmst_type': 'website'

Upvotes: 1

Views: 2047

Answers (1)

Venkatesh Bachu
Venkatesh Bachu

Reputation: 2553

i think the following solution can help you

class VariableSerializer(serializers.ModelSerializer):
    owner_name = serializers.Field(source='owner_id.owner_name')

    class Meta:
        model = Varmst
        resource_name = 'varmst'
        fields = ('varmst_id', 'varmst_type', 'varmst_name', 'varmst_value',
                  'varmst_desc')

    def transform_varmst_type(self, obj, value):
        if obj.varmst_value == 2:
            return "email"
        if obj.varmst_value == 3:
            return "Website"

Upvotes: 1

Related Questions