I am trying to change Model field name in DRF Serializer like alias in SQL. I have tried different methods but cannot succeed.
models.py
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
def alias_alternate_name(self):
return self.alternate_name
serializers.py
class ParkSerializer(serializers.ModelSerializer):
location = serializers.Field(source='alias_alternate_name')
#location = serializers.SerializerMethodField(source='alias_alternate_name')
#alternate_name as location
class Meta:
model = Park
fields = ('id', 'name', 'location')
I have also tried to add alias in Django Queryset but cannot changed.
Updated
This is the exception that i am facing
AttributeError at /ViewName/ 'module' object has no attribute 'Field'
How can I do this?
Thank you
There is a very nice feature in serializer fields and serializers in general called 'source' where you can specify source of data from the model field.
Where serializers.SomeSerializerField can be serializers.CharField as your model suggests but can also by any of the other fields. Also you can put relational fields and other serializers instead and this would still work like charm. ie even if alternate_name was a foreignkey field to another model.
This works with creation, deleting and modification type of requests also. It effectively creates one on one mapping of field name in the serializer and field name in models.
This would work for write operations also
You can use
serializers.SerializerMethodField
:Here is the model Park, which has name and alternate_name fields.
Here is Serializer for Park Model, ParkSerializer. This changes the name of alternate_name to location.
This would however work only for read only fields.