【问题标题】:How do I allow POST to a list_route, but not to the entire ViewSet?如何允许 POST 到 list_route,但不允许 POST 到整个 ViewSet?
【发布时间】:2016-06-23 20:57:30
【问题描述】:

我有一个Game 模型,并且正在为它做相应的 REST 路由,例如GET /gameGET /game/1

我只希望 API 消费者获取现有游戏。我不希望他们能够任意发布新游戏。相反,他们应该走一条特殊的路线,POST /game/upload_schedule

我有以下几点:

class GameViewSet(viewsets.ModelViewSet):
    queryset = Game.objects.all()
    serializer_class = GameSerializer
    http_method_names = ['get', 'head']

    @list_route(methods=['post'])
    def upload_schedule(self, request):
        return Response(["foo"])

但是,当我POST /game/upload_schedule 时,我得到一个方法不允许的错误。原因是http_method_names 阻止了它的发生。如果我将其更改为以下内容:

    http_method_names = ['get', 'head', 'post']

然后POST /game/upload_schedule 路由有效。但是,现在POST /game 也是如此!

我该怎么做?

【问题讨论】:

    标签: django django-rest-framework http-method


    【解决方案1】:

    这是一个 XY 问题。 GameViewSet 应该只处理Games 和专门处理游戏的事情。上传时间表不是游戏列表的属性 - 它是一条单独的路线。因此,将其设为APIView,与GameViewSet 分开:

    class UploadSchedule(APIView):
        def post(self, request):
            raise NotImplementedError()
    

    然后在^upload_schedule$ 下明确路由它。

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      相关资源
      最近更新 更多