Context in Views


In Django REST Framework, the `APIView` class and the `ModelViewSet` class handle the context dictionary differently, which may explain the difference you're observing.


When you use the `APIView` class, the context dictionary is not automatically populated. You need to pass the context explicitly when instantiating the serializer or accessing it within the view methods. For example:


class MyAPIView(APIView):

  def get(self, request, *args, **kwargs):

    serializer = MySerializer(data=request.data, context={'user': request.user})

    # Access the context within the view

    user = self.request.user


In this case, the context is manually passed to the serializer when creating an instance, and it can also be accessed directly from the request object within the view method.


On the other hand, when you use the `ModelViewSet` class, the context dictionary is automatically populated with some default values based on the request and viewset. The context dictionary in a `ModelViewSet` includes information such as the `request` object, the `format` of the request, the `view` instance, and other useful data. This default behavior is implemented in the `GenericAPIView` class, which is the base class for `ModelViewSet`.


class MyModelViewSet(ModelViewSet):

  serializer_class = MySerializer

  queryset = MyModel.objects.all()


In this case, the `ModelViewSet` automatically sets the context dictionary with default values, including the request object. You can access the context within your serializer using `self.context['request']` or `self.context['view']`.


It's worth noting that the behavior of the context dictionary can be customized by overriding the respective methods in the view classes or by creating custom mixin classes. So, if you have additional requirements or need to modify the context, you can override the appropriate methods in your view classes.


date:Oct. 25, 2023