python - Django 休息框架 : @detail_route and @list_route with same name

标签 python django django-rest-framework

我有一个 DRF View 集,想提供详细信息并列出具有相同名称的路由:

class MyViewSet(ViewSet):
    # ...

    @detail_route(['post'])
    def do_stuff(self, request, *args, **kwargs):
        pass

    @list_route(['post'])
    def do_stuff(self, request, *args, **kwargs):
        pass

这显然行不通,因为 list_route 只会覆盖 detail_route

有没有一种简单的方法可以在不使用 manually messing up with the urls 的情况下提供两条路线? ?

最佳答案

我不确定这是否是您要找的,您可以为两者设置相同的 url 路径名:

class MyViewSet(ViewSet):
    # ...

    @detail_route(['post'], url_path='do_stuff')
    def do_stuff_detail(self, request, *args, **kwargs):
        pass

    @list_route(['post'], url_path='do_stuff')
    def do_stuff_list(self, request, *args, **kwargs):
        pass

在第一个中,url 将是 ../"id"/do_stuff,在第二个中,url 将是 ../do_stuff

关于python - Django 休息框架 : @detail_route and @list_route with same name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46178397/

相关文章:

python - 我的 Django 看起来无法识别模板

python - 如何在 django 项目的 settings.py 文件中将身份验证后端设置为默认(扩展 AbstractBaseUser 模型)

python - Django 测试如何检查函数是否未被调用

python - 在Django Rest框架中传递几个参数

python - Python 3 的 int 可以容纳的最大值是多少?

Python的sqlite3的executemany不接受元组列表

python - 如何通过引用pandas中的日期来提取

python - 千位分隔符未在 Django 管理中应用

Django Rest Framework - 如何获取外键的外键字段

python - "Expected a list of items but got type\"字典\"."