title: How Can I Use Two Different Model Serializers With the Same Model?
body: <p>I'm using django-rest-framework. I have a model with a relation. I would like to just display the count of related items when a user hits the <code>/modelname/</code> URL, but show the full related set when a user hits a specific model instance at <code>/modelname/1/</code>.</p>
  
  <p>I can <em>almost</em> get what I want.</p>
  
  <p>I have two serializers, like so:</p>
  
  <pre><code>class DataSetSerializer(serializers.ModelSerializer):
      revisions = serializers.RelatedField(source='datasetrevision_set', many=True)
  
      class Meta:
          model = DataSet
          fields = ('id', 'title', 'revisions')
  
  class ShortDataSetSerializer(serializers.ModelSerializer):
  
      class Meta:
          model = DataSet
          fields = ('id', 'title', 'revisions')
  </code></pre>
  
  <p>If I use the short version, I get the count of revisions (it's a calculated field). If I use the long version, I get the full list of related items as "revisions".</p>
  
  <p>Short:</p>
  
  <pre><code>[{"id": 1, "title": "My Data Set", "revisions": 0}]
  </code></pre>
  
  <p>Long:</p>
  
  <pre><code>[{"id": 1, "title": "My Data Set", "revisions": ["Data Set v1", "Data Set v2"]}]
  </code></pre>
  
  <p>What I want to do is be able to switch between them based on query parameters (url). I tried to set the serializer_class to the ShortDataSetSerializer when the ID was not present, but it overrode all cases, not just the non-ID case.</p>
  
  <pre><code>class DataSetViewSet(viewsets.ModelViewSet):
      serializer_class = DataSetSerializer
      model = DataSet
  
      def get_queryset(self):
         try:
             id = self.kwargs['id']
             queryset = DataSet.objects.filter(id=id)
         except KeyError:
             queryset = DataSet.objects.all()
             # We want to only list all of the revision data if we're viewing a
             # specific set, but this overrides for all cases, not just the one
             # we want.
             self.serializer_class = ShortDataSetSerializer
         return queryset
  </code></pre>
  
  <p>Is there a way I can make this work? I realize I may be approaching this in a totally ridiculous manner, but it seems like there should be an easy solution.</p>
  
  <p>The data example I gave rather abbreviated compared to the real data I'm working with. The end goal is to show a subset of fields in list view, and every field in the GET for a specific ID. This is a read-only API, so I don't need to worry about POST/PUT/DELETE.</p>