lwin
lwin

Reputation: 4460

What is the meaning of detail argument in Django ViewSet?

I create a custom action method in Django ViewSet and I see detail argument. If I set detail=True I can't call this method from URL but if I set detail=False, I can call this method. May I know what is the meaning of detail argument?

Here is my viewset = >

class TimeSheetViewSet(viewsets.ModelViewSet): 
    queryset = TimeSheet.objects.all()
    serializer_class = TimeSheetSerializer

    @action(methods=['get'], detail=True)
    def byhello(self, request):        
        return Response({"From Hello":"Got it"})

Here are router and URL patterns =>

router.register('timesheets_ts', TimeSheetViewSet, base_name='timesheets')

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

Upvotes: 11

Views: 14265

Answers (1)

Higor Rossato
Higor Rossato

Reputation: 2046

As the docs states, if you pass detail=True it means that that router will return you a single object whilst if you don't pass detail=True or pass detail=False it will return a list of objects.

One thing to have in mind is that if you are not doing anything or don’t need a single object in this function, you can set the detail=False

In your case it’d be something like:

@action(methods=['get'], detail=True)
def byhello(self, request, pk=None):
    self.object = self.get_object()        
    return Response({"From Hello":"Got it"})

Upvotes: 22

Related Questions