restframework详细|python基础教程|python入门|python教程
他提供了一些规则,例如:
class GenericAPIView(APIView):
serializer_class = None
queryset = None
lookup_field = 'pk'
filter_backends = api_settings.DEFAULT_FILTER_BACKENDS
pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
def get_queryset(self):
return self.queryset
def get_serializer_class(self):
return self.serializer_class
def filter_queryset(self, queryset):
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
@property
def paginator(self):
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
self._paginator = self.pagination_class()
return self._paginator
他相当于提供了一些规则,建议子类中使用固定的方式获取数据,例如:
class ArticleView(GenericAPIView):
queryset = models.User.objects.all()
def get(self,request,*args,**kwargs):
query = self.get_queryset()
我们可以自己继承GenericAPIView来实现具体操作,但是一般不会,因为更加麻烦。
而GenericAPIView主要是提供给drf内部的 ListAPIView、Create....
class ListModelMixin:
def list(self, request, *args, **kwargs):
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)
class ListAPIView(mixins.ListModelMixin,GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class MyView(ListAPIView):
queryset = xxxx
ser...