slq*_*lqq 4 python django django-rest-framework
我需要在 @action name 方法的最后一个 / 之后传递实例 ID,我真的不知道如何...
我有一个 UserViewSet,访问列表的 url 是:/users/,然后我有一个名为favorite_posts 的操作,它是detail=False因为我正在按当前登录的用户进行过滤,并且该操作是指用户帖子,我希望能够传递 post_id 像/users/favorite_posts/post_id/,因为在这种情况下,它比/users/1/favorite_posts/对我更友好,我可以获得设置detail=True。
有没有办法做到这一点?
您可以在 url 模式中包含参数并user_id传递给您的方法,如下所示:
@action(methods=['post'], detail=False, url_path='favorite_posts/(?P<user_id>\d+)', url_name='favorite-posts')
def get_favorite_post(self, request, user_id):
# Do something
return Response({...})
Run Code Online (Sandbox Code Playgroud)
你可以这样使用它:
@action(methods=['get'], detail=False, url_path='req/(?P<post_id>\d+)')
Run Code Online (Sandbox Code Playgroud)
并在您的方法中获取 post_id,如下所示:kwargs.get('post_id')或者直接传递post_id给您的方法。
@action(methods=['get'], detail=False, url_path='req/(?P<post_id>\d+)')
def get_post(request, post_id):
.....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6822 次 |
| 最近记录: |