LondonAppDev
LondonAppDev

Reputation: 9673

Changing name of json attribute in serializer

How can I change the name of a json field response given by the serializer from the Django Rest Framework?

After following the documentation I tried this, however it didn't work.

from api.models import Countries
from rest_framework import serializers

class CountrySerializer(serializers.Serializer):
    country_geoname_id = serializers.CharField(required=True)
    iso = serializers.CharField(max_length=2L, required=True)
    country_name = serializers.CharField(max_length=64L, required=True)

    def transform_iso(self, obj, value):
        return "country_code"

Basically the JSON response looks like this:

{
    "country_geoname_id": 3041565, 
    "iso": "AD", 
    "country_name": "Andorra"
}, 

And I am trying to change the field iso to country_code.

Upvotes: 0

Views: 1809

Answers (1)

jbub
jbub

Reputation: 2665

You can use the source attribute on the field.

See: http://django-rest-framework.org/api-guide/fields.html#core-arguments

So with your example you would do:

class CountrySerializer(serializers.Serializer):
    country_geoname_id = serializers.CharField(required=True)
    country_code = serializers.CharField(source='iso', max_length=2L, required=True)
    country_name = serializers.CharField(max_length=64L, required=True)

Hope this helps you.

Upvotes: 3

Related Questions