Dynamic views is a efficient way to reduce your amount of serializers.This is achieved because through the viewset that django_dynamic_fields provides, the fields can be selected depending on the action that is being performed
class ArticleViewSet(DynamicViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
action_fields = {
'list' : ('id', ,'title', 'pub_date', 'excerpt'),
'retrieve': ('id', 'title', 'pub_date', 'text', 'author'),
}
- Create your own viewsets using concrete fields per action.
- Create serializers with dynamic fields
- Reusable components.
- Less amount of serializers
Start using django_dynamic_fields is so easy. First we must create our custom serializer and make it inherit from DynamicFieldsModelSerializer.
class ArticleSerializer(DynamicFieldsModelSerializer):
class Meta:
model = Article
fields = '__all__'
Easy as that. Then we must create our custom viewset like the example before.
class ArticleViewSet(DynamicViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
action_fields = {
'list' : ('id', ,'title', 'pub_date', 'excerpt'),
'retrieve': ('id', 'title', 'pub_date', 'text', 'author'),
}
And thats all!! Happy hacking :)