Django REST Framework - pass extra parameter to actions

后端 未结 3 534
梦谈多话
梦谈多话 2021-02-02 09:54

I\'m using Django 2.0 and Django REST Framework

I have created an action method to delete particular object from database

conta

相关标签:
3条回答
  • 2021-02-02 10:18

    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
    
    0 讨论(0)
  • 2021-02-02 10:18

    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))
    ]
    
    0 讨论(0)
  • 2021-02-02 10:31
    @action(methods=['delete'], detail=True)
    def delete_phone(self, request, pk=None):
        contact = get_object_or_404(self.get_queryset(), pk=pk)
        contact.delete()
        return Response({'status': 'success'})
    

    this should work.

    0 讨论(0)
提交回复
热议问题