GenericAPIVIew是所有的Generic View的基类,通过组合mixin来构建不同的Generic View。
GenericAPIVIew
属性
queryset
该属性不应该直接使用 否则该queryset在一次实例化后会cache数据 应该使用get_queryset方法
serializer_class
用于验证和逆序列化和序列化的serializer类 重载该属性或get_serializer_class方法
lookup_field
默认 pk
lookup_url_kwarg
默认和lookup_field相同
pagination_class
filter_backends
方法
get_querysest
get_object
queryset = self.filter_queryset(self.get_queryset())
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
obj = get_object_or_404(queryset, **filter_kwargs)
self.check_object_permissions(self.request, obj)
filter_queryset
get_serializer get_serializer_class get_serializer_context
paginator get_paginated_response paginate_queryset
mixins
ListModeMixin
提供了list方法
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
CreateModelMixin
提供了create方法
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
重载时可只重载perform_create,默认实现为调用serializer.save()
RetrieveModelMixin
提供了retrieve方法 单个对象返回
UpdateModelMixin
提供了update方法 partial_update方法 可以只重载perform_update方法
DestroyModelMixin
提供了destroy方法 可以只重载perform_destroy方法f
具体类
CreateAPIView(mixins.CreateModelMixin, GenericAPIView) post
ListAPIView(mixins.ListModelMixin, GenericAPIView) get
RetrieveAPIView(mixins.RetrieveModelMixin, GenericAPIView) get
DestroyAPIView(mixins.DestroyModelMixin, GenericAPIView) delete
UpdateAPIView(mixins.UpdateModelMixin, GenericAPIView)
put->update patch->partial_update