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

查看:228
本文介绍了在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.

参考

ModelViewSet

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

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