Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use arguments for a custom view in a ModelViewSet

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

I think I would like my function to look like:

@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 am not sure exactly where or how I should be passing these arguments in, or if what I want to do is even right, but this seems like it would be a very common use.

like image 768
InnisBrendan Avatar asked Dec 06 '14 23:12

InnisBrendan


1 Answers

It sounds like you are looking to use query parameters for filtering your queryset. Django REST Framework provides a lot of help with filtering querysets through the filtering backends.

There is a specific section for filtering through the query parameters, which sounds like what you are using for. It uses request.query_params, which is a custom method added by Django REST Framework that collects all of the query parameters that were passed in.

If you are looking for in-url filtering (/api/users/search/:search for instance), then you will need to modify the urls generated for your queryset to provide these extra parameters. Django REST Framework does not provide an easy way to do this using the Router classes, but you can do this by manually registering the urls with Django.

like image 118
Kevin Brown-Silva Avatar answered Sep 20 '22 17:09

Kevin Brown-Silva