Home > Software design >  DRF CreateModelMixin with additional fields
DRF CreateModelMixin with additional fields

Time:11-30

I'm using GenericAPIView with the CreateModelMixin to create a model instance. I need my serializer to add additional fields that aren't defined by the user. My Serializer.create method is already set up for this, but I don't know how to pass fields through to the CreateModelMixin.create method. Here's a minimal version of what I have:

class Foo(mixins.CreateModelMixin, generics.GenericAPIView):
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        return FooSerializer

    def post(self, request):
        return self.create(
            request, requester=request.user  # Additional field
        )

This doesn't work - the requester field isn't passed to FooSerializer.save, so FooSerializer throws an error when it attempts to access requester in FooSerializer.create. Before, I was using APIView and calling the serializer directly, so I could simply:

serializer = FooSerializer(data=request.data)
if serializer.is_valid():
    foo = serializer.save(requester=request.user)

Is there any way to achieve this with the GenericAPIView? I want to embrace DRF's DRY-ness and avoid calling serializers in every endpoint method.

CodePudding user response:

Instead of overriding create method you can override perform_create. Also you may need to define post method:

class Foo(mixins.CreateModelMixin, generics.GenericAPIView):
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        return FooSerializer

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def perform_create(self, serializer):
        serializer.save(requester=self.request.user)
  • Related