Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))  
]
like image 765
lwin Avatar asked Jan 01 '23 18:01

lwin


1 Answers

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"})
like image 99
Higor Rossato Avatar answered Jan 14 '23 07:01

Higor Rossato