Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different fields setting for ModelSerializer in django rest framework

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')
like image 973
peon Avatar asked May 17 '15 10:05

peon


1 Answers

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)
like image 164
Michael B Avatar answered Sep 17 '22 08:09

Michael B