Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use parameters in DRF router

Hello guys so I came to realise that DRF ModelViewSet is a quick way to make rest views, I am trying to use parameters within the router url but the ViewSet does not detect the param

Here is how my viewset looks

class ClientRequests(ModelsViewSet):
    serializer_class = serializers.ClientRequestSerializer

   def get_queryset(self):
      return models.ClientRequest.objects.filter(cliend_id=self.request.kwargs.get('client_id')

now I register the router as below

router = DefaultRouter()
router.register('/<int:client_id/requests', views.ClientRequests, basename='clients request api endpoint')

urlpatterns=[
     path('', include(router.urls))

Is this the right way to use restframework router and how can I pass paramters to the url when using router

like image 727
Ochom Richard Avatar asked Aug 16 '20 16:08

Ochom Richard


People also ask

How do you use a router in DRF?

Routers are used with ViewSets in django rest framework to auto config the urls. Routers provides a simple, quick and consistent way of wiring ViewSet logic to a set of URLs. Router automatically maps the incoming request to proper viewset action based on the request method type(i.e GET, POST, etc).

What is Basename in Django router?

basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.

What is Viewset in Django rest?

A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as . get() or . post() , and instead provides actions such as . list() and .


1 Answers

Use regex notation

router.register(
    r'(?P<client_id>\d+)/requests',
    views.ClientRequests,
    basename='clients request api endpoint'
)
like image 146
JPG Avatar answered Sep 20 '22 15:09

JPG