Search code examples
pythondjangodjango-rest-frameworkjson-api

How to set resource name on an ad-hoc method of Viewset in Django Rest Framework JSON API?


I am using Django 1.10 with DRF 3.5 and Django Rest Framework JSON API 2.1.1. I have a Viewset that follows the normal pattern of a ModelViewset, but I need to add an ad-hoc as follows:

class EnvoiViewSet(viewsets.ModelViewSet):
    queryset = Envoi.objects.none()
    serializer_class = EnvoiSerializer
    filter_class = EnvoiFilter
    ordering_fields = ('date_envoi',)

    # ....

    @decorators.list_route(methods=['post'])
    def ad_hoc_method(self, request):
        #....

My problem is that I want to change the resource name for the method but not for the class. Is this possible with a decorator or something like it ? For example:

@decorators.list_route(methods=['post'])
@resource_name('SpecialEnvoi')
def ad_hoc_method(self, request):
    #....

Solution

  • The ViewSet is the controller of the resource. It doesn't make sense to set a method on a ViewSet and associate it with another resource.

    Either write a function with decorator to make an API entry point or get a new ViewSet for it.