简体   繁体   English

如何创建具有相同路径但不同 HTTP 方法的 2 个动作 DRF

[英]How to create 2 actions with same path but different HTTP methods DRF

So I'm trying to have different actions under the same method, but the last defined method is the only one that work, is there a way to do this?所以我试图在同一方法下进行不同的操作,但最后定义的方法是唯一有效的方法,有没有办法做到这一点?

views.py视图.py

class SomeViewSet(ModelViewSet):
    ...

    @detail_route(methods=['post'])
    def methodname(self, request, pk=None):
    ... action 1

    @detail_route(methods=['get'])
    def methodname(self, request, pk=None):
    ... action 2

The most rational method I've found here :我在这里找到的最合理的方法:

class MyViewSet(ViewSet):
    @action(detail=False)
    def example(self, request, **kwargs):
        """GET implementation."""

    @example.mapping.post
    def create_example(self, request, **kwargs):
        """POST implementation."""

That method provides possibility to use self.action inside of another viewset methods with correct value.该方法提供了在具有正确值的另一个视图集方法中使用self.action可能性。

Are you trying to have actions based on HTTP request type?您是否尝试根据 HTTP 请求类型执行操作? like for post request execute action 1 and for get request execute action 2?像发布请求执行操作 1 和获取请求执行操作 2? If that's the case then try如果是这种情况,请尝试

def methodname(self, request, pk=None):
    if request.method == "POST":
        action 1..
    else 
        action 2..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM