The DRF ModelSerializer already has all the logic to handle this. In your case, you donβt even need to configure to_representation . If you need to configure it, I would recommend calling super first and then setting up the output:
class PersonListSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('foo', 'bar',) def to_representation(self, instance): data = super(PersonListSerializer, self).to_representation(instance) data.update(...) return data
PS if you are interested in knowing how this works, magic doesn't actually happen in ModelSerializer.to_representation . In fact, he does not even implement this method. Its implemented on a regular Serializer . All the magic with Django models actually happens in get_fields , which calls get_field_names , which then takes Meta.fields parameters into account ...
source share