Reputation: 73
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?
Upvotes: 1
Views: 1355
Reputation: 1592
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
Upvotes: 3