Hi,
I'm trying to understand how i can add an additional method to a ViewSet that is routable against a list endpoint rather than a single instance endpoint.
I understand i can mark additional methods on the ViewSet with the @action and @link decorators. From the docs the following example is given
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
@action()
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.DATA)
if serializer.is_valid():
user.set_password(serializer.data['password'])
user.save()
return Response({'status': 'password set'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
This would result in the action then being available at a url similar to
^users/{pk}/set_password/$
Now say i want to add a 'username_available' method to the ViewSet where i can check availability of a given username. Logically the route for this should appear under the list endpoint and not an instance endpoint.
i.e.
^users/username_available/$
rather than
^users/{pk}/username_available/$
as would be the case when using the @link or @action decorators.
What would be the best way to achieve this?
Thanks
Roger.