what's different about list_route and detail_route in django-rest-framework?

后端 未结 3 1534
旧时难觅i
旧时难觅i 2021-02-20 18:06

like title,
what\'s different about list_route and detail_route in django-rest-framework?
if I want to get 1 in url xxx/book

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-20 18:29

    detail_route, is for an instance. What I mean, method generated with detail route, will be appended after an instance method, i.e. a retrieve. {prefix}/{lookup}/

    Check : django drf router doc

    If your model is books and 1 is the id:

    class ParkingViewSet(viewsets.ModelViewSet):
    serializer_class = BookSerializer
    
    def retrieve(self, request, pk=None):
        # Here pk will be 1.
        queryset = Book.objects.get(pk=pk)         
        serializer = BookSerializer(queryset)                         
        return Response({'msg':"",'data':serializer.data, 'status':'OK'})
    

    If xxx is your instance, you should user url_path variable to change default url. Something like this:

    @detail_route(methods=['get'], url_path='(books/?P\d+)')
    

    Then in the method, you will have num as a parmeter

    urls.py, will be generated with default router:

    from django.conf.urls import url, include                                        
    from recharge_card import views                                                  
    from rest_framework.routers import DefaultRouter                                 
    
    # Create a router and register our viewsets with it.                             
    router = DefaultRouter()                                                         
    router.register(r'xxx', views.XxxViewSet, base_name="xxx")  
    
    urlpatterns = [  
        url(r'^api/', include(router.urls)),                                         
    ]                                                                                
    

提交回复
热议问题