pass a parameter into serilazer under ListModelMixin

Question:

I am passing a parameter to a serilaizer like this:

serializer = AttractionTicketSerializer(attraction, context={'api_consumer':request.auth.application})

I have a view which inherits from ListModelMixin, I need to pass this context param to the serilizer as well.

here is a summarized view:

class AttractionView(mixins.ListModelMixin, generics.GenericAPIView):
    authentication_classes = AUTHENTICATION_CLASSES
    permission_classes = [IsAuthenticatedOrTokenHasReadWriteScope]
    queryset = Attraction.objects.all()
    serializer_class = AttractionSerializer

    def get(self, request: Request, *args, **kwargs):
        attractions: Dict[str, Any] = self.list(request, *args, **kwargs)
        return attractions

Is there a way to do it?

Thanx in advance

Asked By: Oz Cohen

||

Answers:

You can override the get_serializer_context() function to add additional context to be passed to the serializer.

class AttractionView(mixins.ListModelMixin, generics.GenericAPIView):
    <...already_defined_attributes...>

    def get_serializer_context(self):
        # you can access self.request here
        # if you need to get some data from your request

        context = super().get_serializer_context()
        context.update({
            'new_key': <new_value>
        })

        return context

You can also override the list function to achieve it.

def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())
    page = self.paginate_queryset(queryset)

    context = self.get_serializer_context()
    context.update({
        'new_key': 'new_value'
    })

    if page is not None:
        serializer = self.get_serializer(page, context=context, many=True)
        return self.get_paginated_response(serializer.data)

    serializer = self.get_serializer(queryset, context=context, many=True)
    return Response(serializer.data)

Based on your specific requirement you can choose any of the above approaches.

Answered By: Vikrant Srivastava