VnC
VnC

Reputation: 2026

Pass params to DRF API View

Is there a way to pass params to serializer_class in GenericAPIView?

As in, when I try to do

class SomeView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = serializers.SomeSerializer(fields=('a', 'b', 'c'))
    lookup_field = 'id'
    lookup_url_kwarg = 'id'

I get the following error:

TypeError: 'SomeSerializer' object is not callable

I've also tried with the following:

def get_serializer_class(self):
    return serializers.SomeSerializer(
        fields=('a', 'b', 'c')
    )

instead of serializer_class, but the same error is triggered.

Any help would be greatly appreciated.

Upvotes: 0

Views: 187

Answers (1)

JPG
JPG

Reputation: 88659

Override the get_serializer_context(...) method

class SomeView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = serializers.SomeSerializer

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['fields'] = ('a', 'b', 'c')
        return context

Upvotes: 1

Related Questions