我在我的 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')
View 集是
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/
因为我正在使用 session 用户信息来过滤数据。是否可以将 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/
应该通过在UserCommentViewSet
中获取profile_id来给出所有评论的列表。所以你的观点将是这样的:
class UserCommentViewSet(CommentViewSet):
def get_queryset(self):
return Comment.objects.filter(owner__id=profile_id)
简单来说,您可以使用 NestedSimpleRouter
获取所有用户、用户详细信息、单个用户发布的所有评论以及评论详细信息。
解决方案:
如果您只需要当前( session )用户评论(因为您不需要所有用户的所有评论),则需要类似以下内容:
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/
将根据需要提供所有评论。
关于python - NestedSimpleRouter 无需在路由器中使用查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65860671/