'Django rest framework: how to override `is_valid` on a serializer created with `many=True`?

I have tried to override the create method on my viewset class in order to be able to create multiple instances of my model at once. The create method now has the following lines:

    def create(self, request, *args, **kwargs):
        ...
        print('Debug 0')
        serializer = self.get_serializer(
            data=request.data,
            many=True
        )
        print('Debug 1')
        serializer.is_valid(raise_exception=True)
        print('Debug 2')
        self.perform_create(serializer)
        print('Debug 3')
        return Response(serializer.data)

If I now try to override the is_valid method within the serializer class, I get surprising behavior. Suppose I now try to override the is_valid method within the serializer class with a simple wrapper:

    def is_valid(self, raise_exception=False):
        print('is_valid was called')
        return super(AlbumSerializer, self).is_valid(raise_exception)

If there are no validation errors then I would expect the message "is_valid was called" to appear after after "Debug 1". To my surprise though, it appears after "Debug 3" suggesting that my override method did not get invoked till after the items were created!

If there is a validation error, then the "is_valid was called" message appears after "Debug 1" as I would expect.

So I am really surprised/confused what is going on here, and would like to know please if there is a special way that you need to go about overriding is_valid if the serializer involves the many=True option. Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source