You can use serializers.SerializerMethodField
:
Here is the model Park, which has name and alternate_name fields.
class Park(models.Model):
name = models.CharField(max_length=256)
alternate_name = models.CharField(max_length=256, blank=True)
objects = models.GeoManager()
class Meta:
db_table = u'p_park'
def __unicode__(self):
return '%s' % self.name
Here is Serializer for Park Model, ParkSerializer. This changes the name of alternate_name to location.
class ParkSerializer(serializers.ModelSerializer):
location = serializers.SerializerMethodField('get_alternate_name')
class Meta:
model = Park
fields = ('other_fields', 'location')
def get_alternate_name(self, obj):
return obj.alternate_name
Additionally, you can use serializers.CharField
with source
attribute:
class ParkSerializer(serializers.ModelSerializer):
location = serializers.CharField(source='other_fields')
class Meta:
model = Park
fields = ('other_fields', 'location')
Django's __
notation to traverse foreign key also works:
location = serializers.CharField(source='OtherModel__other_fields')
The same principle applies if you want to change the return type on the API, so you can do serializers.DecimalField(source=...)
and other field types as well.
This would however work only for read only fields.