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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With