且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DRF-用于查询参数验证的基本Viewset

更新时间:2023-12-03 11:21:58

Class Base class之所以更好的一个原因是,您可以添加自己的派生或至少添加MixIns,因此从纯编码的角度来看,我认为您应该添加自己的MyBaseViewSet并从中派生MyFirstViewsetMySecondViewset.

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