BAE
BAE

Reputation: 8936

Django: same method different url

My url looks like:

/api/v1/files/
/api/v1/files/100

Is it a good practice to use the same function to match them? just like the following:

class FileView(APIView):
    parser_classes = (MultiPartParser,)
    permission_classes = (IsAuthenticated,)

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(FileView, self).dispatch(request, *args, **kwargs)

    def post(self, request, pk = None):
        if pk is not None:
            Do something
        else:
            do something

How to use different functions in Class-based views? Thanks

Upvotes: 0

Views: 861

Answers (1)

Jeff
Jeff

Reputation: 820

I think having separate methods is cleaner than a single method that branches based on the pk. It's easier to understand which logic goes where by just looking at the view's methods rather than having to follow the (albeit simple) control flow.

My first recommendation would be to check out the viewsets that Django Rest Framework provides and look at performing your logic within the given methods it provides. This seems like it would best fit your use case.

Another option would be to look DRF's generic views which are based off these mixins. These allow more control and customization than the viewsets and are sometimes a better option if you don't need all of the functionality provided by the viewsets.

Upvotes: 1

Related Questions