如何在 ViewSet 文档字符串中明确记录可能的 REST 操作?

rra*_*nza 11 django-rest-framework openapi drf-yasg

DRF文档提到了这一点:

请注意,当使用视图集时,基本文档字符串用于所有生成的视图。要为每个视图提供描述,例如列表和检索视图,请使用文档字符串部分,如架构作为文档:示例中所述。

但是链接不好,类似的链接https://www.django-rest-framework.org/api-guide/schemas/没有提到这些“部分”。

我如何在我的单个 Viewset 中清楚地记录我不同的可能的 REST 操作,当它组成时,

class ViewSet(mixins.ListModelMixin,                                            
              mixins.RetrieveModelMixin,                                        
              mixins.CreateModelMixin,                                          
              mixins.UpdateModelMixin,                                        
              ):       
Run Code Online (Sandbox Code Playgroud)

小智 15

在花了很长时间追踪这个之后,我从谷歌来到这里。确实有一种特殊的文档字符串格式来记录 ViewSet 的各个方法。

相关示例必须在某个时候从文档中删除,但我能够在源代码中找到它。它是由函数处理get_descriptionhttps://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/coreapi.py

文档字符串格式基于操作名称(如果定义了 view.action):

"""
General ViewSet description

list: List somethings

retrieve: Retrieve something

update: Update something

create: Create something

partial_update: Patch something

destroy: Delete something
"""
Run Code Online (Sandbox Code Playgroud)

如果 view.action 未定义,则回退到方法名称:get, put, patch,delete

每个新部分都以小写的 HTTP 方法名称开头,后跟冒号。

  • 不幸的是,这对我来说不适用于“ReadOnlyModelViewSet”。 (2认同)

ued*_*mir 5

每个 mixin 都有特定的方法,如mixins.ListModelMixin使用list方法。因此,您可以像这样明确指定文档;

    class ViewSet(mixins.ListModelMixin,                                            
                  mixins.RetrieveModelMixin,                                        
                  mixins.CreateModelMixin,                                          
                  mixins.UpdateModelMixin,):
        queryset = Model.objects.all()
        serializer_class = Serializer
        ...


        def list(self, request, *args, **kwargs):
            """ 
            This endpoints returns list of objects...
            """
            return super(ViewSet, self).list(request, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

如果您没有任何特定逻辑,则调用该super()方法。

  • mixins.RetrieveModelMixinretrieve
  • mixins.CreateModelMixin使用create
  • mixins.UpdateModelMixin使用update方法。