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

Mar*_*ois 6 python django django-rest-framework

所以我尝试在同一方法下执行不同的操作,但最后定义的方法是唯一有效的方法,有没有办法做到这一点?

视图.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
Run Code Online (Sandbox Code Playgroud)

N.C*_*.C. 13

我在这里找到的最合理的方法:

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

    @example.mapping.post
    def create_example(self, request, **kwargs):
        """POST implementation."""
Run Code Online (Sandbox Code Playgroud)

self.action该方法提供了在另一个视图集方法内部使用具有正确值的可能性。


小智 1

您是否尝试根据 HTTP 请求类型执行操作?就像对于 post 请求执行操作 1 和对于 get 请求执行操作 2 一样?如果是这样的话,请尝试

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