Django Rest Framework Add Class Level Method To Api
I am using Django Rest Framework to create my API. I am using @link to return information about a particular object. class SomeClassView(viewsets.ReadOnlyModelViewSet): @link
Solution 1:
The dynamically generated routes using the @link
or @action
decorators are hard-coded to look like /someclass/<pk>/<methodname>/
. You can expose a /someclass/info
endpoint by adding a custom route, e.g.:
class MyRouter(DefaultRouter):
routes = [
Route(
url=r'^{prefix}/((?P<pk>\d+)/)?info$',
mapping={'get': 'info'},
name='{basename}-info',
initkwargs={}
)
] + DefaultRouter.routes
Then your info
method might look like this:
def info(self, request, pk=None):
if pk:
obj = SomeClass.objects.get(pk=pk)
return Response({'info': obj.info()})
else:
objs = SomeClass.objects.filter(pk__in=request.GET.getlist('pk'))
return Response({'infos': [obj.info() for obj in objs]})
(Note the absence of the @link
decorator.)
Post a Comment for "Django Rest Framework Add Class Level Method To Api"