Django 视图中相同 class 中的多个 get 方法

Multiple get methods in same class in Django views

我在同一个 class 中有多个 get 方法。如何创建网址?

Views.py

class DashboardData(viewsets.ViewSet):
      @action(detail=True, methods=['get'])
      def get_total(self, request):
            Total = File.objects.all().count()
            return Response(Total, status=status.HTTP_200_OK)

      def get_done(self, request):
            Done = File.objects.filter(entry=True).count()
            return Response(Done, status=status.HTTP_200_OK)

      def get_not_done(self, request):
            NotDone = File.objects.filter(entry=False).count()
            return Response(NotDone, status=status.HTTP_200_OK)
            
      def get_pending(self, request):
            Pending = File.objects.filter(entry=False).count()
            return Response(Pending, status=status.HTTP_200_OK)

例如: http:///baser_url/dashboard/total_count 应该调用 get_total() 方法 http:///baser_url/dashboard/done_count 应该调用 done_count() 方法。

您可以将这些方法注册为自定义操作并设置 url_path 参数。

示例:

class DashboardData(viewsets.ViewSet):
    @action(methods=['get'], detail=False, url_path='total_count')
    def get_total(self, request):
        Total = File.objects.all().count()
        return Response(Total, status=status.HTTP_200_OK)

    @action(methods=['get'], detail=False, url_path='done_count')
    def get_done(self, request):
        Done = File.objects.filter(entry=True).count()
        return Response(Done, status=status.HTTP_200_OK)
    
    ...

urls.py

router = SimpleRouter()
router.register('dashboard', views.DashboardData, basename='dashboarddata')

您可以使用 @action 装饰器,但使用 detail=False 将 url 添加到视图集的“根”。

# views.py
class DashboardViewSet(viewsets.ViewSet):
    
    @action(detail=False, url_path="download")
    def get_download(self, request):
        pass

# urls.py in your app
router = SimpleRouter()
router.register("dashboard", DashboardViewSet)
urlpatterns = router.urls

从您的示例来看,您似乎可以为每个函数制作一个 APIView,然后使用路径手动添加它们

class DashPendingView(APIView):
    def get(self, request):
        return Response(pending_things)

url_patterns = [
    path("dashboard/pending/", DashPendingView.as_view(), "dash-pending")
]

如果您想更明确地路由视图函数,那么其他方法是:

urlpatterns = [
    path('dashboard/total_count/', DashboardData.as_view({'get': 'get_total'})),
    ...,
    path('dashboard/done_count/', DashboardData.as_view({'get': 'done_count'})),
]