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 可以极大地简化视图的编写过程,避免重复代码,并提高代码的可维护性

相关推荐
优雅一只猫几秒前
Pybullet 安装过程
python
秋秋秋叶4 分钟前
Python学习——【3.1】函数
python·学习
程序员大金17 分钟前
基于SSM+Vue+MySQL的酒店管理系统
前端·vue.js·后端·mysql·spring·tomcat·mybatis
程序员大金27 分钟前
基于SpringBoot的旅游管理系统
java·vue.js·spring boot·后端·mysql·spring·旅游
Hello.Reader33 分钟前
ClickHouse 与 Quickwit 集成实现高效查询
python·clickhouse·django·全文检索
技术无疆42 分钟前
【Python】Anaconda插件:Sublime Text中的Python开发利器
ide·python·编辑器·pip·pygame·sublime text·python3.11
加油=^_^=1 小时前
MySQL基础篇的补充
数据库·python·mysql
Pandaconda1 小时前
【计算机网络 - 基础问题】每日 3 题(十)
开发语言·经验分享·笔记·后端·计算机网络·面试·职场和发展
鸽芷咕1 小时前
【Python报错已解决】ModuleNotFoundError: No module named ‘tensorflow‘
python·机器学习·tensorflow·bug·neo4j
李元豪1 小时前
python 自动化 win11 编程 实现 一键 启动多个软件,QQ浏览器,snipaste,pycharm软件
python·pycharm·自动化