我有这样的API视图:
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/
都与list
网址匹配:
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'),
]
或者您可以尝试stich他们:
urlpatterns = [
path('followers/<int:id>/', FollowersView.as_view(), name='followers-detail'),
path('followers/', FollowersView.as_view(), name='followers'),
]