Django REST Framework - pass extra parameter to actions

后端 未结 3 589
梦谈多话
梦谈多话 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[^/.]+)')
    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
    

提交回复
热议问题