0

I am using Django REST Framework (DRF) for my API. In particular, I have set up several routes using the ModelViewSet, without much additional coding. In particular, I have a route like

/api/v1/collection/<key>

From all the possible keys, I do need to block one specific key, say special. Any request with any HTTP verb to /api/v1/collection/special should result in a HTTP 404 error.

I can think of two approaches:

  • Override some method on the ViewSet hierarchy. Which one?
  • In urls.py, set up a higher-precedence URL route that intercepts this URL, like path("collection/special", view=<404View>, name="collection-exception"). Does this make sense? What would be the appropriate exception view to route to?

What is the recommended approach? Any of the above, or something else?

Ulrich Schuster
  • 1,670
  • 15
  • 24

1 Answers1

0

If you are using the ModelViewSet then you should overwrite the get_queryset() method. If key value is wrong then raise the Exception otherwise return the queryset:

from rest_framework.exceptions import NotFound 

class MyModelViewSet(viewsets.ModelViewSet):
    # ...
    def get_queryset(self):
        key = self.kwargs.get("key")
        if key == "special":
            raise NotFound()
        return MyModel.objecs.filter(pk=key)
pplonski
  • 5,023
  • 1
  • 30
  • 34