Django REST框架 - 无法覆盖ListAPIView中的列表

时间:2016-06-17 10:48:06

标签: python django rest django-rest-framework

我正在使用Django REST Framework来创建一个可以生成PDF文档的端点。 PDF文档将包含与特定Department对应的信息。我有两个所需的功能 - 能够下载PDF文档,并能够在浏览器中预览文档。

由于PDF文档会根据添加到应用程序的数据随时间变化,因此需要在请求时实时生成文档。作为第一步,我正在尝试在GET请求命中以下端点时在远程文件存储位置生成文档:

departments/<department_pk>/result/preview

由于我的端点只应采用GET个请求,因此我使用ListAPIView。我正在尝试覆盖list方法,以便执行我的自定义文档生成逻辑,但看起来永远不会调用该方法。如何将一些自定义文档生成逻辑插入到我的端点中,以便在端点被GET请求命中时执行?

API / urls.py

url(r'^departments/(?P<department_pk>[0-9]+)/result/preview',
    include(result_document_urls.result_document_preview_router.urls,

document_app / urls.py

result_document_preview_router = routers.DefaultRouter()

result_document_preview_router.register(r'^', ResultDocumentDetailView.as_view(),
    base_name='Department')

document_app / views.py

class ResultDocumentDetailView(generics.ListAPIView):

    queryset = Department.objects.all()
    lookup_field = 'department_pk'
    lookup_url_kwarg = 'department_pk'

    def list(self, request, department_pk):
        queryset = self.get_queryset()
        import ipdb; ipdb.set_trace() # this break point is never hit
        department = get_object_or_404(queryset, department_pk=department_pk)
        ...generate document logic...
        return Response(status=status.HTTP_200_OK)

2 个答案:

答案 0 :(得分:2)

用下面的代码替换list方法,我认为它会起作用

class ResultDocumentDetailView(generics.ListAPIView):

    queryset = Department.objects.all()
    lookup_field = 'department_pk'
    lookup_url_kwarg = 'department_pk'

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        import ipdb; ipdb.set_trace() # this break point is never hit
        department = get_object_or_404(
            queryset, department_pk=kwargs.get('department_pk')
        )

        ...generate document logic...

        return Response(status=status.HTTP_200_OK)

有关更多参考,请参阅重写方法“list”

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L35

答案 1 :(得分:1)

document_app/urls.py中,您错误地将ResultDocumentDetailView作为参数而不是视图集传递。

路由器while registering接受ViewSet而不是APIView

  

register()方法有两个必需参数:

     

prefix - 用于此组路由的URL前缀   viewset - 视图集类

此外,由于您只对retrieve方法感兴趣,因此您只需创建ResultDocumentRetrieveView并将相应的网址添加到urls.py,而无需创建ResultDocument路由器。 (当您要处理listdetail请求时,通常会使用路由器。)

class ResultDocumentRetrieveView(generics.RetrieveAPIView):

    queryset = Department.objects.all()
    lookup_field = 'department_pk'
    lookup_url_kwarg = 'department_pk'

    def retrieve(self, request, department_pk):
        department = self.get_object()
        ...generate document logic...    
        return Response(status=status.HTTP_200_OK)

<强> urls.py

url(r'^departments/(?P<department_pk>[0-9]+)/result/preview', ResultDocumentRetrieveView.as_view())