django - NestedSimpleRouter 没有在路由器中使用查找
问题描述
我在我的 url.py 中使用了类似以下的 drf-nested-router
router = SimpleRouter()
profile_router = routers.NestedSimpleRouter(router, r'profile', lookup='user')
profile_router.register(r'comments', UserCommentViewSet, basename='profile-comments')
视图集是
class UserCommentViewSet(CommentViewSet):
def get_queryset(self):
return Comment.objects.filter(owner=self.request.user)
所以 URL 是这样的,
mydomain.com/profile/{profile_id}/comments/
它给了我正确的结果。但是下面的 URL 也给了我正确的结果,
mydomain.com/profile/{anything}/comments/
因为我正在使用会话用户信息来过滤数据。是否可以使 URL 像
mydomain.com/profile/comments/
提前致谢。
解决方案
根据您的代码:
router = SimpleRouter()
# router.register('users', UserViewSet, 'user')
profile_router = routers.NestedSimpleRouter(router, r'profile', lookup='user')
profile_router.register(r'comments', UserCommentViewSet, basename='profile-comments')
您以错误的方式解释了这一点。这是您可以使用的方法NestedSimpleRouter
mydomain.com/profile/ # list all the users.
mydomain.com/profile/{profile_id} # retrieve particular user based on profile_id/user_id/pk.
mydomain.com/profile/{profile_id}/comments/ # list all the comments belong to a particular user (not the current session user) based on profile_id/user_id.
mydomain.com/profile/{profile_id}/comments/{comment_id} # retrieve particular comment based on comment_id.
这个网址:
mydomain.com/profile/{anything}/comments/
正在工作,因为您正在过滤owner = request.user
.
这个网址:
mydomain.com/profile/{profile_id}/comments/
应该通过获取 profile_id 来给出所有评论的列表UserCommentViewSet
。所以你的观点会是这样的:
class UserCommentViewSet(CommentViewSet):
def get_queryset(self):
return Comment.objects.filter(owner__id=profile_id)
简单来说,您可以NestedSimpleRouter
用来获取所有用户、用户详细信息、单个用户发布的所有评论和评论详细信息。
解决方案:
如果您只需要当前(会话)用户评论(因为您不需要所有用户的所有评论),您需要类似:
router = SimpleRouter()
router.register(r'profile/comments', UserCommentViewSet, basename='profile-comments')
是UserCommentViewSet
:
class UserCommentViewSet(CommentViewSet):
def get_queryset(self):
return Comment.objects.filter(owner=self.request.user)
然后,这个网址:
mydomain.com/profile/comments/
将根据需要给出所有评论。
推荐阅读
- javascript - 即使在浏览器选项卡关闭后仍保留令牌
- c++ - 如何在 C++ 中从反向的向量中显示行的内容?
- javascript - 通过本地网络创建个人分机和主机
- react-native - 如何在 React Native 中前后播放交错动画?
- python - 对用户定义的类列表进行多处理?
- autodesk-forge - Autodesk Forge 查看器 - 添加自定义文本输入
- c++ - 编译时我的简化功能不起作用
- javascript - 如何在javascript行中添加按钮
- javascript - 如何在 componentDidMount 方法中传递多功能
- linux - 错误:initcaps [Errno 2] iptables v1.6.0:无法初始化 iptables 表“过滤器”:表不存在(您需要 insmod 吗?)