Python – django rest framework – using detail_route and detail_list

djangodjango-rest-frameworkpythonrouting

In my code I have a viewset for the User.
I want is to allow only Read operations (/users/42 and /users/) which the ReadOnlyModelViewSet does just fine.

In addition, I want to have a /users/register URL that I can POST to in order to register a new User.

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @list_route(methods=['post'])
    def register(request):
        serializer = UserSerializer(data=request.DATA)
        if serializer.is_valid():
            user = User.objects.create_user(
                username = serializer.init_data['username'],
                password = serializer.init_data['password'],
            )

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Couple of questions:

  • Would this be this the right way of doing that?

  • Is there a specific signature for a method if I put it in a list_route or the detail_route decorator? because in the detail_route examples its always the same signature for the method: method_name(self, request, pk=None):

thanks!

Best Answer

detail_route and detail_list will get deprecated on DRF 3.0 instead use @action:

from rest_framework.decorators import action
    @action(methods=['POST'], detail=True)
    def sale(self):
       ...

Use detail=True when this method will account for a single instance of the Model represented by that endpoint and False when it needs to represent a Queryset of that model