Django REST Framework Serializers - to_representation()


DRF tip:

If you want to change the output of the serializer, you can override the to_representation function of the serializer.

For example:

class MovieSerializer(serializers.ModelSerializer):
    class Meta:
        model = Movie
        fields = '__all__'

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['likes'] = instance.liked_by.count()

        return representation

For more, review Custom Outputs.