【问题标题】:Django restframework generic viewset not working with get and get detail views with the same url_path and url_nameDjango rest 框架通用视图集不适用于获取和获取具有相同 url 路径和 url 名称的详细视图
【发布时间】:2021-11-21 05:16:43
【问题描述】:

如果使用相同或不同的方法但 details 值不同,我如何使 DRF Generic viewset 中的两个视图使用相同的 url_paths 和 url_names,例如必须都可以是 Get 方法但应该有 @ 987654324@ 和 details=False 在上面

示例代码更清晰;

 @action(methods=["get"], detail=False, url_path="list-users", url_name="users")
    def get_users(self, request):
        # code here
 @action(methods=["get"], detail=True, url_path="users", url_name="users")
    def get_user(self, request, id):

        # code here

get_users 使用此端点 -> {{base_url}}/{{prefix}}/users

get_user 不适用于 -> {{base_url}}/{{prefix}}/{{user-id}}/users

但如果我将 url_path 和 url_name 更改为其他内容,例如 -> single-user

然后获取单个用户的端点工作 -> {{base_url}}/{{prefix}}/{{user-id}}/single-user

我该如何解决这个问题以使用户和用户具有相同的 url_name 和 url_path,因为操作的详细信息分别为 False(users) 和 True(user)

NB; Also please note that this viewset does not make use of any model

【问题讨论】:

  • url_name 在每次浏览时都必须是唯一的

标签: django django-rest-framework django-views django-rest-viewsets


【解决方案1】:

所以我想通了,DRF 实际上有 Routing 额外的 HTTP 方法用于额外的操作,可以在这里查看; https://www.django-rest-framework.org/api-guide/viewsets/#routing-additional-http-methods-for-extra-actions

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2022-01-04
    • 2022-08-08
    • 1970-01-01
    • 2017-09-13
    • 2016-12-15
    相关资源
    最近更新 更多