Django REST框架 - 将额外参数传递给操作

时间:2018-05-19 12:22:29

标签: django django-rest-framework

我正在使用Django 2.0Django REST Framework

我创建了一个从数据库中删除特定对象的操作方法

联系人/ views.py

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated, AdminAuthenticationPermission,)

    # others actions goes here

    @action(methods=['delete'], detail=False, url_path='delete_phone/<phone_pk>/')
    def delete_phone(self, request, pk=None):
        contact = self.get_object()
        print(contact)
        print(pk)
        print(self.kwargs['phone_pk'])
        return Response({'status': 'success'})

应用/ urls.py

router.register(r'contacts', ContactViewSet, 'contacts')

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

但是当我访问

DELETE: http://url/api/contacts/delete_phone/1/

出现page not found错误。

在错误页面中,已尝试的网址格式

中有列表
api/ ^contacts/delete_phone/<phone_pk>//$ [name='contacts-delete-phone']
api/ ^contacts/delete_phone/<phone_pk>\.(?P<format>[a-z0-9]+)/?$ [name='contacts-delete-phone']

3 个答案:

答案 0 :(得分:3)

使用drf-nested-routers

解决了问题

对于需要它的人,请安装插件并配置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))
]

答案 1 :(得分:3)

如果您不愿意/不愿意/不愿意安装drf-nested-routers,则可以这样做:

@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)

技巧是将正则表达式放在装饰器的url_path参数中,并将其传递给装饰器(避免仅使用pk,否则它将与第一个pk冲突

经过测试:

Django==2.0.10
djangorestframework==3.9.0

答案 2 :(得分:0)

@action(methods=['delete'], detail=False)
def delete_phone(self, request, pk=None):
    contact = get_object_or_404(self.get_queryset(), pk=pk)
    contact.delete()
    return Response({'status': 'success'})

这应该有效。