DRF路由组件分析

本文详细比较了在DjangoRestFramework中使用APIView和继承ViewSet(包括ModelViewSet)进行路由配置的方法,以及利用SimpleRouter和include创建URL模式。同时讨论了如何使用action装饰器处理额外的URL路径和自定义操作。
摘要由CSDN通过智能技术生成

DRF路由组件分析

在之前进行drf开发时,对于路由我们一般进行两种配置:

  • 视图继承APIView

    from django.urls import path
    from app01 import views
    
    urlpatterns = [
        path('api/users/', views.UserView.as_view()),  # APIView
    ]
    
  • 视图继承 ViewSetMixin(GenericViewSet、ModelViewSet)

    from django.urls import path, re_path, include
    from app01 import views
    
    urlpatterns = [
        path('api/users/', views.UserView.as_view({"get":"list","post":"create"})),
        path('api/users/<int:pk>/', views.UserView.as_view({"get":"retrieve","put":"update","patch":"partial_update","delete":"destory"})),
    ]
    

    对于这种形式的路由,drf中提供了更简便的方式:

    from rest_framework import routers
    from app01 import views
    
    router = routers.SimpleRouter()				# routers.urls 所有的路由信息
    router.register(r'api/users', views.UserView)
    
    urlpatterns = [
        # 其他URL
        # path('xxxx/', xxxx.as_view()),
    ]
    
    urlpatterns += router.urls
    

    也可以利用include,给URL加前缀:

    from django.urls import path, include
    from rest_framework import routers
    from app01 import views
    
    router = routers.SimpleRouter()
    router.register(r'users', views.UserView)
    
    urlpatterns = [
        path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
        # 其他URL
        # path('forgot-password/', ForgotPasswordFormView.as_view()),
    ]
    

额外的URL

from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action


class XXXModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"

        
class XXXView(ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = XXXModelSerializer
	
    # detail=False: 生成URL时后面不带id
    # @action(detail=False, methods=['get'], url_path="yyy/(?P<xx>\d+)/xxx")
    # def get_password(self, request, xx, pk=None):
    #     print(xx)
    #     return Response("...")

    # @action(detail=True, methods=['get'], url_path="yyy/(?P<xx>\d+)/xxx")
    # def set_password(self, request, xx, pk=None):
    #     print(xx)
    #     return Response("...")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值