from rest_framework import generics
from rest_framework import permissions
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.pagination import LimitOffsetPagination
# 第四层方式,使用的最多
class ProductListByCategoryView(generics.ListAPIView):
'''
产品按类别列表
'''
serializer_class = ProductListSerializer
# 允许访问权限 permissions.AllowAny 允许所有人访问
permission_classes = (permissions.AllowAny,)
# 对列表进行排序(restframework生成的排序列表,通过get方式的ordering传递) SearchFilter(搜索功能)
filter_backends = (OrderingFilter, SearchFilter)
# 排序方式
ordering_fields = ('category', 'manufacturer', 'created', 'sold')
# 搜索字段
search_fields = ('description', 'model')
# 默认排序
ordering = ('id',)
# 用于前端指定一页数据显示多少条内容
pagination_class = LimitOffsetPagination
def get_queryset(self):
# 此方法用于判断前端是否传递内容,如果没传递,则默认查询所有, 如果传递了,则按要求进行查询
category = self.request.query_params.get('category', None)
if category is not None:
queryset = Product.objects.filter(category=category)
else:
queryset = Product.objects.all()
return queryset
# 第三层使用方法 有时需求不能按照model进行,则需要第三层的方式进行优化
# class SnippetList(APIView):
# '''
# LC (查询以及增加)
# '''
# def get(self,request, format=None):
# snippets = Snippet.objects.all()
# serializer = SnippetSerializer(snippets, many=True)
# return Response(serializer.data)
#
# def post(self,request,format= None):
# serializer = SnippetSerializer(data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
#
# class SnippetDetail(APIView):
# '''
# RUD
# '''
# def get_object(self,pk):
# try:
# return Snippet.objects.get(pk=pk)
# except Snippet.DoesNotExist:
# raise Http404
#
# def get(self,request,pk,format=None):
# snippet = self.get_object(pk)
# serializer = SnippetSerializer(snippet)
# return Response(serializer.data)
#
# def put(self,request,pk,format=None):
# snippet = self.get_object(pk)
# serializer = SnippetSerializer(snippet,data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data)
# return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
#
# def delete(self,request,pk,format=None):
# snippet = self.get_object(pk)
# snippet.delete()
# return Response(status=status.HTTP_204_NO_CONTENT)