Detailed DRF route without PC

I'd like to create a detailed route that displays the current user's data.

If I use a custom router:

class CustomRouter(routers.DefaultRouter):
    def __init__(self, *args, **kwargs):
        super(CustomRouter, self).__init__(*args, **kwargs)

        self.routes.append(
            routers.Route(url=r'^{prefix}/current{trailing_slash}',
                          mapping={'get': 'current'},
                          name='{basename}-current',
                          initkwargs={'suffix': 'Detail'}))


rest_router = CustomRouter()
urlpatterns = [
    url(r'^', include(rest_router.urls)),
]

It works, and I can access the registered user at /api/users/current/.

However, if I use mine CustomUserand register all mine UserViewSet(which goes down from viewsets.ReadOnlyModelViewSet):

rest_router.register(r'users', viewsets.UserViewSet)

my route current/stops working. Is there a way to add a custom detail route that does not require pk?

Edit : my second approach was to add @list_route, which actually returns only one object instead of one. It does not require a special router at all, just an additional method on mine UserViewSet:

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    @list_route(methods=['get'])
    def current(self, request):
        return Response(self.serializer_class(request.user).data)

, , : ?

+4

Source: https://habr.com/ru/post/1652994/


All Articles