DjangRestFramework:为ModelViewSet的单独函数创建单独的URL



我在Django Rest Framework中有一个ModelViewset:

class UserViewset(viewsets.ModelViewSet):
queryset = models.User
serializer_class = serializers.User

其路由器:

router = routers.DefaultRouter()
router.register(r'user', views.UserViewset)

我想为这个视图集的创建、更新、列表和检索功能提供单独的URL:

/user/register/            : POST (create new user)
/user/<pk>/profile         : GET (retrieve profile of user)
/user/<pk>/profile/update/ : PATCH (update profile of user)
/user/list                 : GET (get list of users)

如何实现(使用路由器或URL(?

您可以使用以下工具来完成此操作:

from rest_framework.decorators import action

class UserViewset(viewsets.ModelViewSet):
queryset = models.User
serializer_class = serializers.User
# GET: /user/register/
@action(detail=False, url_path='register/')
def user_register(self, request):
...
# GET: /user/<pk>/profile
@action(detail=True, methods=['get'])
def profile(self, request, pk=None):
...
# PATCH: /user/<pk>/profile/update/
@action(detail=True, methods=['patch'], url_path='profile/update/')
def profile_update(self, request, pk=None):
...
# GET: /user/list 
@action(detail=False, url_path='list/')
def user_list(self, request, *args, **kwargs):
# You can do super().list(request, *args, **kwargs) here, up to you
...

您可以从以下网站了解更多信息:

https://www.django-rest-framework.org/api-guide/viewsets/#marking-路由的额外操作https://www.django-rest-framework.org/api-guide/routers/#routing-用于额外操作

相关内容

  • 没有找到相关文章

最新更新