【问题标题】:DRF ModelViewSet is possible to create custom @action with same url and different methodsDRF ModelViewSet 可以使用相同的 url 和不同的方法创建自定义 @action
【发布时间】:2021-06-09 10:05:45
【问题描述】:

我有带有@action 装饰器的自定义函数,用于使用 GET 和 DELETE 两种方法进行路由。

如果代码在同一个函数中,一切正常,我可以通过简单的 if 运行不同的操作:

    @action(methods=['GET', 'DELETE'], detail=False, url_path='current', url_name='profile-current',
            permission_classes=[IsAuthenticated])
    def get_current_profile(self, request: Request, **kwargs) -> Response:
        if self.request.method == 'DELETE':
        ...

但是我想将代码分成两个函数,仍然具有相同的路由,但方法不同。

如果我将代码分成两个函数和相同的 url-path 和不同的方法,其中一个方法返回方法不可用错误。

我是否在这里遗漏了什么,或者无法按照我认为应该工作的方式创建方法。

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    你可以尝试像这样拆分这两种方法

    GET方法

        @action(
            methods=['GET'],
            detail=False,
            url_path='current',
            url_name='profile-current',
            permission_classes=[IsAuthenticated]
        )
        def get_current_profile(self, request: Request, **kwargs):
            """Get current profile"""
    

    删除方法

    
        @get_current_profile.mapping.delete
        def delete_current_profile(self, request, **kwargs):
            """Delete current profile"""
    
    

    链接:Doc

    【讨论】:

    • 你值得被选中。非常感谢
    【解决方案2】:

    您可以尝试将函数中的两个方法分开,如下所示:

        @action(
            methods=['GET', 'DELETE'],
            detail=False,
            url_path='current',
            url_name='profile-current',
            permission_classes=[IsAuthenticated]
        )
        def get_current_profile(self, request: Request, **kwargs):
            if request.method == "GET":
                """Get current profile"""
            elif request.method == "DELETE":
                """Delete current profile"""
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 2020-10-17
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 2011-10-13
      相关资源
      最近更新 更多