[Django]-Django REST Framework – pass extra parameter to actions

6👍

Solved the problem using drf-nested-routers

For those who need it, install the plugin and configure urls.py

from rest_framework_nested import routers

router = routers.SimpleRouter()
router.register(r'contacts', ContactViewSet, 'contacts')
contact_router = routers.NestedSimpleRouter(router, r'contacts', lookup='contact')
contact_router.register(r'phone_number', ContactPhoneNumberViewSet, base_name='contact-phone-numbers')

api_urlpatterns = [
    path('', include(router.urls)),
    path('', include(contact_router.urls))
]

81👍

In case you can’t/don’t want/whatever install drf-nested-routers, you could achieve the same by doing:

@action(detail=True,
        methods=['delete'],
        url_path='contacts/(?P<phone_pk>[^/.]+)')
def delete_phone(self, request, phone_pk, pk=None):
    contact = self.get_object()
    phone = get_object_or_404(contact.phone_qs, pk=phone_pk)
    phone.delete()
    return Response(.., status=status.HTTP_204_NO_CONTENT)

The trick is to put the regex in url_path parameter of the decorator and pass it to the decorated method (avoid using just pk or it will collide with the first pk)

Tested with:

Django==2.0.10
djangorestframework==3.9.0

1👍

Perhaps this has changed since this question was asked, but this works for me in REST Framework 3.13.

@action(methods=['get'], detail=False, url_path='my_action/(?P<my_pk>[^/.]+)')
def my_action(self, request, my_pk=None):
    return Response()

Resulting in the following entry in urlconf

^my_viewset/my_action/(?P<my_pk>[^/.]+)/$ [name='my-viewset-my-action']
👤Ryan

Leave a comment