[Django]-Django REST Framework @detail_route not working as expected

5๐Ÿ‘

โœ…

You need to use @list_route decorator instead of @detail_route decorator.

This will generate the url movie/highlight/.

Using @list_route decorated method generates the url of type {prefix}/{methodname}/ whereas detail_route decorated method generateds url of type {prefix}/{lookup}/{methodname}/. Here methodname is name of your method and lookup is the lookup value on which lookup is performed to get the object for detail view.

class MovieViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Movie.objects.all().order_by('-title')
    serializer_class = MovieSerializer

    # use list_route decorator
    @list_route(renderer_classes=(renderers.StaticHTMLRenderer,))
    def highlight(self, request, *args, **kwargs):
        snippet = "Highlight"
        return Response(snippet)
๐Ÿ‘คRahul Gupta

0๐Ÿ‘

If you register your URLs using routers.DefaultRouter(), it will generate the URL /movie/pk/highlight instead of /movie/highlight. If you want a custom URL other than the pre-generated one, use URL mapping.

Leave a comment