Django rest framework 自定义url

一、自定义增删改查外的方法和路由

使用 from rest_framework.viewsets import GenericViewSet, ViewSet 这两个模块。

示例:使用 GenericViewSet 以用户修改密码为例

python 复制代码
# view.py
from rest_framework.viewsets import GenericViewSet

class CustomerOperation(GenericViewSet):

    @action(detail=False, methods=['post'])
    def set_password(self, request, pk):
        return return_200(_('Successfully change password'))

# urls.py
from rest_framework import routers

router = routers.DefaultRouter()
router.register('', CustomerOperation)

urlpatterns = [
    # 方法一
    path('<str:pk>/', include(router.urls)),
    # 方法二
    path('<str:pk>/set_password', AloneCustomerOperation.as_view({'post': 'set_password'})),
]
定义 url 使用的提交类型,两种方法

方法一、@action(detail=False, methods=['post']) 修饰函数直接在方法前面定义提交方式即可。

方法二、path('<str:pk>/set_password', AloneCustomerOperation.as_view({'post': 'set_password'})), 定义url,set_password 是 url 要请求的方法,post 是请求的方式

区别:

方法一会自动把 view 类中标记 action 的所有方法自动生成路由。路由名就是方法名称。

方法二是当有一些个性化定义路由时使用

二、自定义 drf 中提供的 list create retrieve update destroy方法的路由

drf 提供两个类
ReadOnlyModelViewSet: 只有 Retrieve 和 List
ModelViewSet: 有 Create、Retrieve、Update、Destroy、List 方法

当然也可以自定义想用的方法使用 from rest_framework import mixins 中的 CreateModelMixin RetrieveModelMixin UpdateModelMixin DestroyModelMixin ListModelMixin 五个方法来自定义。还需要在继承 'GenericViewSet'。

示例:

python 复制代码
@method_decorator(name="retrieve", decorator=.....)
from rest_framework.viewsets import ReadOnlyModelViewSet

class AAAList(ReadOnlyModelViewSet):

    serializer_class = AAASerializers
    queryset = AAA.objects.all()

    # 重构 list  也可以使用默认的 list
    def list(self, request):
        queryset = self.get_queryset()
        serializer = CustomerProductTypeQuota(queryset, many=True)
        return Response(serializer.data)

定义路由方式和上面相同

注意\color{red}{注意}注意:当使用method_decorator

swagger_auto_schema 去修改 api 文档页面时 name 对应的是方法的名字

相关推荐
biuyyyxxx1 小时前
Python自动化办公学习笔记(一) 工具安装&教程
笔记·python·学习·自动化
极客数模1 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
小鸡吃米…2 小时前
机器学习中的代价函数
人工智能·python·机器学习
Li emily3 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
m0_561359674 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
Ulyanov4 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
2401_838472514 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
CoLiuRs5 小时前
语义搜索系统原理与实现
redis·python·向量·es
zhihuaba5 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
u0109272715 小时前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python