禁用 ViewSet 中的一个方法,django-rest-framework [英] Disable a method in a ViewSet, django-rest-framework

查看:21
本文介绍了禁用 ViewSet 中的一个方法,django-rest-framework的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ViewSets 有自动的方法来列出、检索、创建、更新、删除……

ViewSets have automatic methods to list, retrieve, create, update, delete, ...

我想禁用其中的一些,我想出的解决方案可能不是一个好的解决方案,因为 OPTIONS 仍然声明那些是允许的.

I would like to disable some of those, and the solution I came up with is probably not a good one, since OPTIONS still states those as allowed.

知道如何以正确的方式做到这一点吗?

Any idea on how to do this the right way?

class SampleViewSet(viewsets.ModelViewSet):
    queryset = api_models.Sample.objects.all()
    serializer_class = api_serializers.SampleSerializer

    def list(self, request):
        return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
    def create(self, request):
        return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)

推荐答案

ModelViewSet的定义是:

class ModelViewSet(mixins.CreateModelMixin, 
                   mixins.RetrieveModelMixin, 
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet)

所以与其扩展 ModelViewSet,不如直接使用您需要的任何东西?例如:

So rather than extending ModelViewSet, why not just use whatever you need? So for example:

from rest_framework import viewsets, mixins

class SampleViewSet(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    viewsets.GenericViewSet):
    ...

使用这种方法,路由器应该只为包含的方法生成路由.

With this approach, the router should only generate routes for the included methods.

参考资料:

模型视图集

这篇关于禁用 ViewSet 中的一个方法,django-rest-framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆