[Django]-Get all action names from ViewSet (drf)

2πŸ‘

βœ…

I don’t think there is a direct way to get all the actions specified in a ViewSet class. But, the Routers are usually generating the URLs in a similar way. So, I’m going to use the DRF Routers here,

from rest_framework.routers import SimpleRouter

router = SimpleRouter()
routes = router.get_routes(YourViewsetClass)
action_list = []
for route in routes:
    action_list += list(route.mapping.values())
distinct_action_list = set(action_list)
πŸ‘€JPG

1πŸ‘

I’m using rest_framework version 3.11.2 and there you can do it like that:

actions = [action for action in YourViewsetClass.get_extra_actions()]
action_names = [action.__name__ for action in YourViewsetClass.get_extra_actions()]
action_url_names = [action.url_name for action in YourViewsetClass.get_extra_actions()]
πŸ‘€binaryEcon

Leave a comment