我有以下视图集:
class AuthorViewSet(viewsets.ModelViewSet):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
permission_classes = [permissions.AllowAny]
# note that no methods are overridden
我想drf_yasg
生成自定义模式,以便将所有操作方法标记为Authors
.
文档说我的选择是通过声明和使用来装饰每个方法,@swagger_auto_schema
如下所示:
class AuthorViewSet(viewsets.ModelViewSet):
# ...
@swagger_auto_schema(tags=["Authors"])
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
或者像这样使用Django @method_decorator
:
@method_decorator(name="list", decorator=swagger_auto_schema(tags=["Authors"]))
class AuthorViewSet(viewsets.ModelViewSet):
# ...
这两种选择都需要繁琐的重复,我想避免这种情况。
我也尝试实现自己的装饰器:
def decorate_viewset_methods(names, decorator):
if names == "__all__":
names = [
"create",
"retrieve",
"update",
"partial_update",
"destroy",
"list",
]
def decorate(cls):
for name in names:
method = getattr(cls, name)
setattr(cls, name, decorator(method))
return cls
return decorate
但这并不完全奏效。
所以我的问题是如何一次装饰所有的动作方法?