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

相关推荐
Victor3561 小时前
Redis(28)Redis的持久化文件可以跨平台使用吗?
后端
Victor3561 小时前
Redis(29)如何手动触发Redis的RDB快照?
后端
乘乘凉2 小时前
Python中函数的闭包和装饰器
前端·数据库·python
爱隐身的官人6 小时前
爬虫基础学习-爬取网页项目(二)
前端·爬虫·python·学习
快乐就是哈哈哈8 小时前
《一文带你搞懂ElasticSearch:从零到上手搜索引擎》
后端·elasticsearch
刘恒1234567898 小时前
Pycharm
ide·python·pycharm
大鸡腿同学9 小时前
身弱:修炼之路
后端
bobz9659 小时前
cpu 调度 和 gpu 调度
后端
AirMan9 小时前
深入揭秘 ConcurrentHashMap:JDK7 到 JDK8 并发优化的演进之路
后端·面试
bobz9659 小时前
Linux CPU 调度模型
后端