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')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With