How to use arguments for custom view in ModelViewSet

I would like to create a custom view in my ModelViewSet using the @list_route decorator that takes multiple arguments. I cannot find an example of this.

I guess I would like my function to look like this:

@list_route()
def my_list(self, request, arg1, arg2, arg3):
    models = Model.objects.all().filter( """do some filtering with my args""" )
    serializer = ModelSerializer(models, many=True, context={'request': request})
    return Response(serializer.data)

      

Again, I don't know exactly where or how I should be passing these arguments, or if what I want to do is even correct, but it looks like it would be a very common use.

+3


source to share


1 answer


It looks like you are trying to use request parameters to filter your request. The Django REST Framework provides great help in filtering requests through filter servers .

There is a specific section for filtering through query parameters , which sounds like you are using. It uses request.query_params

which is a custom method added by the Django REST Framework that collects all the request parameters that were passed.



If you are looking for filtering in a URL (for example /api/users/search/:search

), you will need to change the URLs generated for your request to provide these additional parameters. The Django REST Framework does not provide an easy way to do this using classes Router

, but you can do it by manually registering URLs with Django .

+7


source







All Articles