一视图组件
restframework可以轻松完成对某个数据的增删改查的目的,在继承viewsets.ModelViewset后,只需要配置数据管理对象和序列化器即可,
class BookModelView(viewsets.ModelViewSet): queryset = models.Book.objects.all() serializer_class = BookSerializer
上面的方法是直接继承restframework提供的方法来实现对数据的增删改查的目的,根据前端提交请求的方式不同,通过get、post、put、delete、等实现
使用这种方法的时候,路由需要传参,视图组件在继承ViewsetMixin之后可以进行路由传参
url(r‘api/$‘, views.BookModelView.as_view({"get": "list", "post": "create"})), url(r‘api/(?P<pk>\d+)‘, views.BookModelView.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),
路由传参可以使用路由组件来更加方便的进行达到目的
from rest_framework.routers import DefaultRouter router =DefaultRouter() router.register(r‘book‘, views.BookModelView)
urlpatterns += router.urls
我们也可以通过自己重写方法来实现这些功能
class GenericAPIView(APIView): queryset = None serializer_class = None def get_queryset(self): return self.queryset.all() def get_serializer(self, *args, **kwargs): return self.serializer_class(*args, **kwargs) class ListModelMixin(object): def list(self, request): queryset = self.get_queryset() ser_obj = self.get_serializer(queryset, many=True) return Response(ser_obj.data) class CreateModelMixin(object): def create(self, request): ser_obj = self.get_serializer(data=request.data) if ser_obj.is_valid(): ser_obj.save() return Response(ser_obj.validated_data) return Response(ser_obj.errors) class RetrieveModelMixin(object): def retrieve(self, request, id): book_obj = self.get_queryset().filter(id=id).first() ser_obj = BookSerializer(book_obj) return Response(ser_obj.data) class UpdateModelMixin(object): def update(self, request, id): book_obj = self.get_queryset().filter(id=id).first() ser_obj = self.get_serializer(instance=book_obj, data=request.data, partial=True) if ser_obj.is_valid(): ser_obj.save() return Response(ser_obj.validated_data) return Response(ser_obj.errors) class DestroyModelMixin(object): def destroy(self, request, id): book_obj = self.get_queryset().filter(id=id).first() if not book_obj: return Response("删除的对象不存在") book_obj.delete() return Response("") class ListCreateAPIView(GenericAPIView, ListModelMixin, CreateModelMixin): pass class RetrieveUpdateDestroyAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin): pass class ModelViewSet(ViewSetMixin, ListCreateAPIView, RetrieveUpdateDestroyAPIView): pass
在通过调用自己写的ModelViewSet实现
class BookModelView(ModelViewSet): queryset = models.Book.objects.all() serializer_class = BookSerializer
原文地址:https://www.cnblogs.com/wszxdzd/p/10004116.html
时间: 2024-09-30 04:15:40