python - NestedSimpleRouter 无需在路由器中使用查找

标签 python django django-rest-framework drf-nested-routers

我在我的 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/

相关文章:

python - 在序列化器中创建访问另一个模型属性的新字段

python - Dataframe - 在按日期分组的行中查找第一个 0

Python 字符串分割

python - 在单个相关对象上使用多个条件进行过滤

python - 如何在Django中使用pathlib.Path?

python - 在 Django 中返回 HttpResponse 后删除 tmp 文件

python - 使用 Python BeautifulSoup 库解析 Span HTML 标签中的信息

python - Pig脚本无法注册UDF

django - DRF Serializer - 如何返回外键的字段?

Django Rest_framework "Got AttributeError when attempting to get a value for field Process"