python - 如何将自定义 DRF api View 映射到多个 url?

标签 python django django-rest-framework

我有一个像这样的 API View :

class FollowersView(ListAPIView, RetrieveAPIView):
    serializer_class = FollowerSerializer
    queryset = Follower.objects.all()

如何让它在每个操作中使用不同的 URL - 列出和检索?

urlpatterns = [
    path('followers/', FollowersView.as_view(), name='followers'),    #all requests are captured here
    path('followers/<int:id>/', FollowersView.as_view(), name='followers-detail'),
]

现在每个请求都被列表操作捕获。

最佳答案

您需要在网址末尾添加 $ 符号,否则 followers/followers/123/ 都会匹配 列表网址:

urlpatterns = [
    path('followers/$', FollowersView.as_view(), name='followers'),
    path('followers/<int:id>/', FollowersView.as_view(), name='followers-detail'), 
]

或者您可以将其放在单个网址中:

urlpatterns = [
    re_path('^followers(?:/(?P<pk>[0-9]+))?/$',
        FollowersView.as_view(),
        name='followers'),
]

或者你可以尝试缝合它们:

urlpatterns = [       
    path('followers/<int:id>/', FollowersView.as_view(), name='followers-detail'), 
    path('followers/', FollowersView.as_view(), name='followers'),
]

关于python - 如何将自定义 DRF api View 映射到多个 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877672/

相关文章:

python - Django 模型形式 - 多个模型

没有模型的 Django REST 框架序列化程序

django - CORS 和 JWT 有什么区别

python - Tensorflow:导入预训练模型(mobilenet、.pb、.ckpt)

python - 使用 pandas DataFrame 在箱线图上绘制线条

python - POST 方法执行正确的发布,然后重新呈现整个页面

python - 如何使用 try- except 计算 numpy 数组中的相邻单元格?

javascript - Django/Ajax/Javasdript JSON.parse 将字符串转换为 JavaScript 对象

python - 类型错误 : detail() missing 1 required positional argument: 'request'

Django 1.9.2 测试客户端问题