Django Rest Framework: Passing Context in Viewsets

Viewed 295

Viewsets are convenient because we can do stuff like this and get a fully working serializer:

class StoreObjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]
    queryset = StoreObject.active_objects.all()
    serializer_class = serializers.StoreObjectSerializer

Unfortunately, as far as I know– to pass the context into the serializer we need to do things like this:

PostSerializer(data=request.data, context={'request': request})

Which means we need to manually override every convenient method provided by ViewSets (as far as I know). Is there a way to inject the context into every serializer while still keeping Viewsets convenient?

1 Answers

By default, request is being sent to any Generic View and ViewSet. You can check the source code in GitHub as well. So you do not have to inject them in every view. If you want to pass extra context, then override get_serializer_context(...) method:

class StoreObjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    ...

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['custom_context'] = 'Your custom context'
        return context
Related