更新时间:2023-12-03 11:21:58
Class Base class之所以更好的一个原因是,您可以添加自己的派生或至少添加MixIns,因此从纯编码的角度来看,我认为您应该添加自己的MyBaseViewSet
并从中派生MyFirstViewset
和MySecondViewset
.
One reason for why Class Base class are better is exactly that you can add your own derivation or at least add MixIns, so from the pure coding point of view, I think you should just add your own MyBaseViewSet
and have MyFirstViewset
and MySecondViewset
derive from it.
也就是说,考虑覆盖get_queryset
而不是list
,并使用ListAPIView
,这样您将获得一些默认行为,只是返回一个空数组,或者如果您确实要通过异常返回错误,请执行以下操作:
That said, consider overwriting get_queryset
instead of list
, and use ListAPIView
so you get some default behavior, and just return an empty array or if you really want to return an error, through an exception:
class MyBaseViewSet(generics.ListAPIView):
serializer_class = YourSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
some_param = self.request.query_params.get('someparam')
if not some_param:
raise exceptions.PermissionDenied