Django REST Framework(十二)视图集-GenericViewSet

GenericViewSet 是 Django REST Framework 中的一个类,它结合了 GenericAPIViewViewSetMixin 的功能。它的主要目的是简化视图代码,通过将独特的代码作为类属性进行抽象,使代码更加可复用

直接使用 ViewSet 的不便之处

直接使用 ViewSet 时,像 listretrievecreateupdatedestroy 这样的方法都需要手动编写。而这些方法与 Mixin 扩展类提供的方法同名,因此我们可以通过继承相应的 Mixin 扩展类来复用这些方法。然而,Mixin 扩展类依赖于 GenericAPIView,所以我们还需要继承 GenericAPIView

GenericViewSet 通过继承 GenericAPIViewViewSetMixin,帮助我们完成了这样的继承工作,使我们可以直接搭配 Mixin 扩展类使用,而无需手动编写这些方法。

示例

下面是如何使用 GenericViewSet 的示例:

python 复制代码
from rest_framework.viewsets import GenericViewSet

class BookView(GenericViewSet):

    def list(self, request):

        books = Book.objects.all()
        bs = BookSerializer(instance=books, many=True)
        return Response(bs.data)

    def create(self, request):
        bs = BookSerializer(data=request.data)
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

    def retrieve(self, request, pk):
        book = Book.objects.get(pk=pk)
        bs = BookSerializer(instance=book)
        return Response(bs.data)

    def update(self, request, pk):
        instance = Book.objects.get(pk=pk)
        bs = BookSerializer(instance=instance, data=request.data)
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

    def delete(self, request, pk):
        Book.objects.get(pk=pk).delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

urls :

python 复制代码
from django.urls import path, re_path

from vset.views import BookView

urlpatterns = [
    # path("set", views.BookView.as_view({"http请求":"视图方法"})),
    path("books/", BookView.as_view({
        "get": "list",
        "post": "create"
    })),
    re_path("^books/(?P<pk>\d+)$", BookView.as_view({
        "get": "retrieve",
        "put": "update",
        "delete": "delete",
    })),
]

集合我们上面学习的模型扩展类,实现简写操作,视图,代码:

python 复制代码
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin


class BookView(GenericViewSet, ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin,
                          DestroyModelMixin):
    queryset = Book.objects
    serializer_class = BookSerializer

这种设置允许你在不手动编写每个方法的情况下,定义 CRUD 操作,充分利用 Mixin 扩展类和 GenericViewSet 的功能。

详细解释
  1. GenericViewSet 继承自 GenericAPIViewViewSetMixin,并且可以与各种 Mixin 扩展类一起使用,如 ListModelMixinCreateModelMixinRetrieveModelMixinUpdateModelMixinDestroyModelMixin
  2. queryset 属性定义了视图集将使用的查询集。在这个示例中,BookView 将使用 Book 模型的所有对象。
  3. serializer_class 属性定义了视图集将使用的序列化器类。在这个示例中,BookView 将使用 BookSerializer
  4. list 方法 返回所有图书的列表。
  5. create 方法 创建一本新图书。
  6. retrieve 方法 返回指定 ID 的图书。
  7. update 方法 更新指定 ID 的图书。
  8. delete 方法 删除指定 ID 的图书。

通过上述配置,使用 GenericViewSet 可以极大地简化视图的编写过程,避免重复代码,并提高代码的可维护性

相关推荐
汤姆小白2 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
To_OC6 小时前
手写 AI 编程 Agent 的命令执行工具:我被 child_process 坑出来的实战经验
后端·node.js·agent
向日的葵0068 小时前
langchain的Tools教程(三)
python·langchain·tools
逝水无殇9 小时前
C# 异常处理详解
开发语言·后端·c#
言乐610 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
YUS云生10 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
智写-AI10 小时前
真实有效的免费降英文AI工具服务商
人工智能·python
yuhuofei202111 小时前
【Python入门】了解掌握Python中函数的基本使用
python
考虑考虑11 小时前
Sentinel安装
java·后端·微服务
IT_陈寒11 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端