0

May i know how to setup method with multiparameter like=>

@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)

this shiftid is the parameter.

Here is my router=>

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

Normally my url will be like =>

api/shift_mas/

Now i would like to do like =>

api/shift_mas/byshiftid/?shiftid="shift1" something like that.

I try like that =>

@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)

But its always say 404 not found.

My requirement is to select the record by shiftid.So how can I setup the route like that?

lwin
  • 3,784
  • 6
  • 25
  • 46

2 Answers2

1

If you're using DRF, you might take a look at Django-filters. It offers an easy way to add filters to your views/viewsets:

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')

Then url requests filter the results:

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

I've been using this in production for about six months with no issues.

gregory
  • 10,969
  • 2
  • 30
  • 42
  • I tried your way but i got this error: 'Meta.fields' contains fields that are not defined on this FilterSet: s, h, i, f, t, d. I set filterset_fields=('shiftid') – lwin Jul 25 '19 at 06:37
  • @Jze You get that error when you don't have a trailing comma, change it to: `filterset_fields=('shiftid',)` – gregory Jul 25 '19 at 15:00
0

Well, this part is called Query string:

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

You can access the value of query string by:

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

So you don't need to define any url path and you can remove the extra parameter byshiftid method from for this as well.

ruddra
  • 50,746
  • 7
  • 78
  • 101