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

相关推荐
uzong3 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
笨笨聊运维4 小时前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite4 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
q***69774 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
小毛驴8504 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
哈里谢顿4 小时前
Django 中间件(Middleware)详解
django
闲人编程4 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_457760005 小时前
Python 数据结构
数据结构·windows·python
IUGEI5 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#