首页 > 解决方案 > 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/

提前致谢。

标签: djangodjango-rest-frameworkdrf-nested-routers

解决方案


根据您的代码:

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/

将根据需要给出所有评论。


推荐阅读