I have a serializer
class CategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ["id", "name", "name_en", "about", "parent",]
It is used in two locations:
- All Categories API: Used to view rich details about the categories.
- All Posts API: Used to know the name of the category only.
In my Posts Serializer, I used:
class PostListSerializer(serializers.ModelSerializer):
categories = CategoryListSerializer(many=True, )
class Meta:
model = Post
fields = ["id", "title", "description", "publish_date", "thumbnail", "owner", "categories", ]
And in my Post ViewSet:
class PostViewSet(ReadOnlyModelViewSet):
queryset = Post.objects.all().filter(is_published=True)
serializer_class = PostListSerializer
This returns All posts with All Categories Details mentioned in CategoryListSerializer
, as it should be.
Question:
I want the PostListSerializer
to return only the "name" field from the related Categories, without having to define another CategorySimpleSerializer
that selects "name" field only. (I still need the CategoryListSerializer
fields in another API)
Is it possible to do that?
Note: This is only an example, I'll have more usecases for this and want to know ahead if i'll have to create many custom "to-be-nested" Serialzers, to avoid exposing some unnecessary data to some of the APIs. It seemed like lots of redundant update work if a model or API needs change later.
As Mentioned by @mtzd in the comments:
Creating a generic Dynamic Serializer Class (As in DRF Docs here) worked!
My Category Serializer Looks like this now:
and in
PostListSerializer
Categories variable, I added the fields attribute only:So now I can manage what fields to show to each View API i use, from a Single Model Serializer that i can modify/update once.