How to apply throttling just to create action in DRF viewsets?

Viewed 413

I have a viewset and I want to apply throttling to only create action of that viewset and I don't want it to be applied to update, destroy, retrieve and etc...

class UserViewSet(viewsets.ModelViewSet):
    # should only be applied to the create action
    throttle_classes = [SomeThrottle] 
    ...
1 Answers

As described in Introspecting ViewSet actions [DRF docs] you can inspect the action attribute to set the throttle_classes based on the current action by overriding the get_throttles method:

class UserViewSet(viewsets.ModelViewSet):
    def get_throttles(self):
        if self.action == 'create':
            throttle_classes = [SomeThrottle]
        else:
            throttle_classes = []  # No throttle for other actions
        return [throttle() for throttle in throttle_classes]
Related