Django REST Framework(九)GenericAPIView视图子类
GenericAPIView
是 Django REST Framework (DRF) 中一个非常重要的类,它提供了常用的通用视图功能。通过继承 GenericAPIView
,可以轻松地构建 RESTful API。
用法
-
导入所需模块:
from rest_framework import generics from .models import BookModel from .serializers import BookModelSerializer
-
创建视图:
你可以创建一个视图类,继承
GenericAPIView
,并指定相应的查询集和序列化器。class BookModelListCreateView(generics.GenericAPIView): queryset = BookModel.objects.all() serializer_class = BookModelSerializer def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=201)
-
使用 Mixins:
GenericAPIView
可以与 mixins 一起使用,以实现更具体的功能,如获取、更新、删除等。from rest_framework import mixins class BookModelListCreateView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = BookModel.objects.all() serializer_class = BookModelSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs)
-
组合使用:
DRF 提供了多种组合类,如
ListCreateAPIView
、RetrieveUpdateDestroyAPIView
,这些都是GenericAPIView
和 mixins 的组合。from rest_framework import generics class BookModelListCreateView(generics.ListCreateAPIView): queryset = BookModel.objects.all() serializer_class = BookModelSerializer
常用功能
get_queryset()
:返回要查询的对象集合。get_serializer()
:返回用于序列化和反序列化数据的序列化器实例。perform_create()
:处理对象创建的逻辑,通常在create()
方法中调用。
例子
from rest_framework import generics
from .models import BookModel
from .serializers import BookModelSerializer
class BookModelDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = BookModel.objects.all()
serializer_class = BookModelSerializer
原文地址:https://blog.csdn.net/yjjpp2301/article/details/140456211
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!