Django视图集rou中的多参数方法

2024-04-19 18:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以知道如何用多参数设置方法吗,比如=>

@action(methods=['get'], detail=True)
    def byshiftid(self, request,shiftid): 
        print("Hello World")       
        query = self.get_queryset().get(shiftid=shiftid)
        serializer = ShiftSummarySerializer(query,many=True)
        return Response(serializer.data)

这个shiftid是参数。你知道吗

这是我的路由器=>

router.register('shifts_mas', ShiftViewSet, base_name='shifts')

通常我的url会是=>

api/shift_mas/

现在我想做喜欢=>

api/shift_mas/byshiftid/?shiftid="shift1"类似的。你知道吗

我试着这样做=>

@action(methods=['get'], detail=True,url_path='/(?P<shiftid>)')
    def byshiftid(self, request,shiftid): 
        print("Hello World")       
        query = self.get_queryset().get(shiftid=shiftid)
        serializer = ShiftSummarySerializer(query,many=True)
        return Response(serializer.data)

但它总是说404找不到。你知道吗

我的要求是通过shiftid选择记录。那么如何设置这样的路由呢?你知道吗


Tags: gtselftruegetrequestdefactionquery
2条回答

如果您使用的是DRF,那么可以看看Django过滤器。它提供了一种向视图/视图集添加过滤器的简单方法:

from django_filters import rest_framework as filters
from rest_framework import viewsets

class ProductList(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_fields = ('category', 'in_stock')

然后url请求过滤结果:

api/production/?category='foobar'&instock='Y'

我已经在生产中使用了六个月没有问题了。你知道吗

这个部分叫做^{}

api/shift_mas/byshiftid/?shiftid="shift1"

您可以通过以下方式访问查询字符串的值:

shiftid = request.GET.get('shiftid', None)

因此,您不需要定义任何url路径,也可以为此从中删除额外的参数byshiftid方法。你知道吗

相关问题 更多 >