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

相关推荐
92year5 小时前
用Google ADK从零搭一个能调工具的AI Agent:Python实操全过程
python·ai·mcp
woxihuan1234565 小时前
SQL删除数据时存在依赖关系_设置外键级联删除ON DELETE
jvm·数据库·python
Jetev6 小时前
如何确定SQL字段是否为空_使用IS NULL与IS NOT NULL
jvm·数据库·python
蛐蛐蛐6 小时前
昇腾910B4上安装新版本CANN的正确流程
人工智能·python·昇腾
m0_702036536 小时前
mysql如何处理不走索引的OR查询_使用UNION ALL优化重写
jvm·数据库·python
庞轩px6 小时前
第七篇:Spring扩展点——如何优雅地介入Bean的创建流程
java·后端·spring·bean·aware·扩展点
ltl6 小时前
Q/K/V 三件套:把 Bahdanau 抽象成一个公式
后端
2401_846339566 小时前
MySQL在云环境如何选择存储类型_SSD与高性能云盘配置建议
jvm·数据库·python
2601_957780847 小时前
Claude 4.6 对阵 GPT-5.4:2026 开发者大模型 API 选型深度解析
人工智能·python·gpt·ai·claude
2601_957780847 小时前
GPT-5.5 深度解析:2026年4月OpenAI旗舰模型的技术跨越与商业决策指南
大数据·人工智能·python·gpt·openai