Py学习  »  Django

Django视图中同一类中的多个get方法

alucor-it • 3 年前 • 1584 次点击  

我在同一个类中有多个get方法。如何创建URL?

意见。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()方法。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129310
 
1584 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Andrew
Reply   •   1 楼
Andrew    3 年前

你可以使用 @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 对于每个函数,然后使用path手动添加它们

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

url_patterns = [
    path("dashboard/pending/", DashPendingView.as_view(), "dash-pending")
]
Aprimus
Reply   •   2 楼
Aprimus    3 年前

您可以将这些方法注册为自定义操作,并设置 url_路径 参数

例子:

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)
    
    ...

网址。py

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

Ersain
Reply   •   3 楼
Ersain    3 年前

如果希望更明确地路由视图函数,则其他方法是:

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