【问题标题】:Pass extra parameter to custom actions将额外参数传递给自定义操作
【发布时间】:2020-06-12 19:13:49
【问题描述】:

您好,我的视图集中有一个自定义操作,但除了 detail=True,我不确定如何向路由添加更多参数我想要执行操作以过滤某个类别的医生,网址应该类似于doctor/categories/<int:category_id> 但我在尝试添加参数时找不到页面(404)

  @action(detail=False, methods=['get'])
    def categories(self, request,*args, **kwargs):
        """ 
        Get a list of doctor profiles from an specific category 
        """


        data = {
            'profile' : 'doctor',
        }
        return Response(data, status=status.HTTP_200_OK)

编辑--

当尝试这样的事情时

@action(detail=False, methods=['get'], url_path='categories/<int:category_id>')
    def categories(self, request,*args, **kwargs):

我仍然收到错误 404,在检查可用路线时我发现了这个

v1/ ^profiles/doctors/categories/<int:category_id>/$ [name='profiles/doctors-categories']

v1/ ^profiles/doctors/categories/<int:category_id>\.(?P<format>[a-z0-9]+)/?$ [name='profiles/doctors-categories']

所以网址在那里......但也许我输入错了?

这是我的网址

http://127.0.0.1:8000/v1/profiles/doctors/categories/1

这是我的 urls.py(简体)

from sanitas.views import doctor_schedule as doctor_schedule_views

router = DefaultRouter()

router.register(r'profiles/doctors', doctor_profiles_views.DoctorProfileViewset, basename='profiles/doctors')


urlpatterns = [ 
    path('', include(router.urls)),
]

希望大家能帮帮我

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    来自Routing for extra actions的DRF文档

    默认情况下,URL 模式基于方法名,而 URL name 是 ViewSet.basename 和连字符的组合 方法名称。如果您不想对其中任何一个使用默认值 值,您可以改为将 url_pathurl_name 参数提供给 @action 装饰器。

    所以,使用 url_path 作为,

    @action(detail=False, methods=['get'], url_path=r'categories/(?P&ltcategory_id>\d+)')
    def categories(self, request, *args, **kwargs):
        return Response({'msg': 'ok', 'kwargs': kwargs})

    现在使用端点:/profiles/doctors/categories/1234/

    注意: url_path 值必须在与正则表达式兼容的字符串中,如果是path 兼容字符串,DRF 将无法识别

    【讨论】:

    • 不工作我做了这个@action(detail=False, methods=['get'], url_path='categories/&lt;int:category_id&gt;'),但是当转到/profiles/doctors/categories/1 的网址时,我得到了一个找不到页面(404)当查看可用的网址时,我发现了这个`v1/ ^profiles/医生/类别//$ [name='profiles/doctors-categories'] ` 和这个 ` v1/ ^profiles/doctors/categories/\.(?P[a -z0-9]+)/?$ [name='profiles/doctors-categories'] ` 不知道是什么意思。
    • 如果您解释了您提供的代码如何回答问题,这将是一个更好的答案。
    • 如何绑定网址?你能显示你的 urls.py 吗? @AnibalCardozo
    • @ArakkalAbu 我刚刚编辑了我的原始帖子以包含 urls.py
    【解决方案2】:

    您需要将 url_path 值更改为

    url_path=r'categories/(?P<category_id>\d+)' 
    

    而不是

    url_path=r'categories/<category_id>)'
    

    你需要category_id 参数在你的操作中

    @action(detail=False, methods=['get'], url_path=r'categories/(?P<category_id>\d+)')
    def categories(self, request,category_id, *args, **kwargs):
    #here you can access your category_id param
    return Response(...)
    

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多