ListModelMixin
class ListView(ListModelMixin, GenericAPIView): queryset = Model.objects.all() serializer_class = Ser def get(self, request): return self.list(request)
CreateModelMixin
class CreateSer(serializers.ModelSerializer): class Meta: model = model fields = '__all__' class CreateView(GenericAPIView, CreateModelMixin): serializer_class = CreateSer def post(self, request): return self.create(request)
RetrieveModelMixin
以lookup_field为 orm 过滤字段,查询lookup_url_kwarg对应值的一条数据详情,需要提供queryset参数作为查询的位置
class DetailView(GenericAPIView, RetrieveModelMixin): queryset = model.objects.all() serializer_class = DetailSer lookup_field = 'pk' lookup_url_kwarg = 'pk' def get(self, request, pk): return self.retrieve(request)
-
设置的路由及访问的路由如下所示
path('detailview/<int:pk>/', DetailView.as_view()), # http://127.0.0.1:8000/detailview/1/
UpdateModelMixin
实现更新的话也需要lookup_field和lookup_url_kwarg来确定被更新数据,使用 put/post 等方式提交数据即可,对比创建的混合类
class UpdateView(GenericAPIView, UpdateModelMixin): queryset = model.objects.all() serializer_class = UpdateSer lookup_field = 'pk' # 被更新数据过滤字段 lookup_url_kwarg = 'pk' # 被更新数据过滤条件参数值 def put(self, request, pk): return self.update(request)
请求该视图时,不光需要链接传参数,还需要在请求体中提供更新后的数据
# put http://127.0.0.1:8000/updateview/1/ { "name":... "age": ... }
注意:如果需要对序列化器字段进行局部更新,而不是所有数据都会更新,那么可以在update参数位置传递partial参数,传递为True
self.update(request,partial=True)
DestroyModelMixin
比如删除一个已存在数据,和更新一样,需要有数据的过滤条件,不传就是用固定那套 pk 的机制查询
class DeleteView(GenericAPIView, DestroyModelMixin): queryset = model.objects.all() def delete(self, request, pk): return self.destroy(request)