Q:

Django Rest framework: Limit number of fields while using serialzer as nested object

A serializer in my code is used at two different places.
First Use : Direct
    class FirstSerializer(serializers.ModelSerializer):
        class Meta(object):
            model = FirstSerializer
            fields = ('first_name', 'last_name', 'line1', 'line2',)

Second Use : Within another serializer
    class SecondSerializer(serializers.ModelSerializer):
        first_serilizer = FirstSerializer(many=True, read_only=True)
    class Meta(object):
        model = SecondSerializer

In first usecase, I need all fields.
In second usecase, while using it as nested object I want to exclude 'line2' from the list of fields.

A:

I will subclass the 'FirstSerializer' class to limit code duplication and specify only the needed fields on the 'PartialFirstSerializer',
class FirstSerializer(serializers.ModelSerializer):

     class Meta:
        model = FirstModel

class PartialFirstSerializer(FirstSerializer):

    class Meta:
        fields = ('first_name', 'last_name', 'line1')

class SecondSerializer(serializers.ModelSerializer):
    first_serializer = PartialFirstSerializer(many=True, read_only=True)

    class Meta:
        model = SecondModel

If you are looking for a more generic solution the DRF docs shows you how to create a DynamicFieldsModelSerializer, that takes a fields attribute. 
http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    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(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        if fields is not None:
           # 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)

class FirstSerializer(DynamicFieldsModelSerializer):

     class Meta:
        model = FirstModel

class SecondSerializer(serializers.ModelSerializer):
    first_serializer = FirstSerializer(fields=('first_name', 'last_name', 'line1'), many=True, read_only=True)

    class Meta:
        model = SecondModel

