8

I have a simple ModelSerializer, and I want to use different fields for lists/details like below, is it possible?

class ItemSerializer(serializers.ModelSerializer):
  class Meta:
    model = Item
    list_fields = ('id', 'name')
    detailed_fields = ('id', 'name', 'long_column')
1

1 Answer 1

7

Update: May 23, 2019

A better answer can be found here: stackoverflow.com/a/44070743/225767

(thanks for the comment @uhbif19)

Original answer:

What I would personally do is have a different serializer for lists vs. detail. The ModelViewSet has a list() and retrieve() method. In the example below, I overrode the retrieve() method and set the serializer_class attribute to the declared "detail" serializer. When it calls super(), we are now using the detail serializer. The list() will continue to use the ItemListSerializer.

On a side note, if you are going to continue using this pattern, it might be in your best interest to create your own ModelViewSet class with custom list_fields and detail_fields.

from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet

class ItemListSerializer(ModelSerializer):
    class Meta:
        model = Item
        fields = ('id', 'name')


class ItemDetailSerializer(ModelSerializer):
    class Meta:
        model = Item
        fields = ('id', 'name', 'long_column')


class ItemViewSet(ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemListSerializer

    def retrieve(self, request, *args, **kwargs):
        self.serializer_class = ItemDetailSerializer
        return super(ItemViewSet, self).retrieve(request, *args, **kwargs)
Sign up to request clarification or add additional context in comments.

2 Comments

I guess that this code may broke, if you will user list right after retrieve call. To use different serializers for different endpoints proper approach will be to override get_serializer_class() . stackoverflow.com/a/44070743/225767
As of 2019, this overriding get_serializer_class is definitely the better solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.