from rest_framework import serializers


class FieldSelectorSerializer(serializers.ModelSerializer):
    """
    Special serializer class. Instances accept a `fields` keyword argument
    to set which fields shall be serialized.
    """
    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)

        # Instantiate the superclass normally
        super(FieldSelectorSerializer, self).__init__(*args, **kwargs)

        if fields:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)
