Django REST Framework-将额外的参数传递给动作 [英] Django REST Framework - pass extra parameter to actions
本文介绍了Django REST Framework-将额外的参数传递给动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Django 2.0
和 Django REST Framework
我已经创建了一种从数据库删除特定对象的操作方法
I have created an action method to delete particular object from database
contacts / 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/
它给出了页找不到
错误。
It gives page not found
error.
在错误页面中,有尝试过的网址格式
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']
推荐答案
对于那些需要它的人,安装插件并配置 urls.py
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))
]
这篇关于Django REST Framework-将额外的参数传递给动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文