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.
class ParkSerializer(serializers.ModelSerializer):
location = serializers.SomeSerializerField(source='alternate_name')
class Meta:
model = Park
fields = ('other_fields', 'location')
Where serializers.SomeSerializerField can be serializers.CharField as your model suggests but can also be 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.
class ParkSerializer(serializers.ModelSerializer):
locations = AlternateNameSerializer(source='alternate_name', many=true)
class Meta:
model = Park
fields = ('other_fields', 'locations')
class AlternateNameSerializer(serializers.ModelSerialzer):
class Meta:
model = SomeModel
This works with the creation, deletion, and modification requests too. It effectively creates one on one mapping of the field name in the serializer and field name in models.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…