1

I'm structuring a Django API with rest framework, I read the docs and DRF only makes a crud (get, post, patch, delete) from a model. Now the deal is how I can make custom actions with DRF.

Example:

api/v1/model/custom_action

Code:

class DistrictViewSet(viewsets.ModelViewSet):
      queryset = District.objects.all()
      serializer_class = DistrictSerializer

      def custom_action(request, param):
          # do many actions and return as Json Object

urls.py

url(r'api/v1/', include(router.urls))

Where router

router.register(r'model',api.ModelViewSet)

I'm correct with this or I need to create another modelview, customize the code and add it to router list?

1 Answer 1

3

You can add custom actions as you have done but you may need the @action decorator to configure the url to apply to a single object, or many. @action(detail=True) adds pk to the url, as it applies to one object.

The url is generated from the action name, so for example

@action(detail=True)
def custom_action(self):
    pass

Would yield the url ^<app_name>/{pk}/custom_action/$

You may find this useful: https://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! It worked. Reading the docs again to check if I miss some :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.