【问题标题】:How to get url to action method from ModelViewSet(Django Rest Framework) with reverse function?如何使用反向功能从 ModelViewSet(Django Rest Framework)获取 url 到操作方法?
【发布时间】:2019-09-25 14:43:26
【问题描述】:

我有这个 ModelViewSet 类:

class DriveInvoiceViewSet(viewsets.ModelViewSet):
    filter_fields = ('location_id', 'logical_deleted')
    permission_classes = (UserCanManageFacilityPermission,)
    pagination_class = None

    def get_serializer_class(self):
        ...

    def get_queryset(self):
        ...

    @action(detail=False, methods=['GET'])
    def get_subtotals_by_unit(self, request):
        invoices_list = self.filter_queryset(self.get_queryset())
        grouped_invoices = get_subtotals_by_unit(invoices_list)

        return Response(grouped_invoices)

如何从反向函数获取 URL 以测试 get_subtotals_by_unit 操作?

路由器注册的ViewSetrouter.register('drive_invoices', DriveInvoiceViewSet, base_name='drive_invoices')

【问题讨论】:

    标签: python django testing django-rest-framework


    【解决方案1】:

    如下改变 action 装饰器,

    class DriveInvoiceViewSet(viewsets.ModelViewSet):
        # other code
        @action(detail=False, methods=['GET'], url_path="/some/path/", url_name="some-view-name")
        def get_subtotals_by_unit(self, request):
            invoices_list = self.filter_queryset(self.get_queryset())
            grouped_invoices = get_subtotals_by_unit(invoices_list)
            return Response(grouped_invoices)

    因此,DRF 将创建一个 url 模式,其视图名称的语法为 <router_base_name>-<action_view_name>

    因此,在您的情况下,视图名称将是 drive_invoices-some-view-name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多