方法一:
from .models import Goods
from .serializers import GoodsSerializer
#自己封装了Response
from rest_framework import mixins
from rest_framework import generics
class GoodsListView(mixins.ListModelMixin,generics.GenericAPIView):
"""
返回商品列表页
"""
#得到所有的商品
queryset = Goods.objects.all()[:10]
#序列化器
serializer_class = GoodsSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
方法二:
from .models import Goods
from .serializers import GoodsSerializer
from rest_framework import generics
#ListAPIView已经实现了get方法
class GoodsListView(generics.ListAPIView):
"""
返回商品列表
"""
#得到所有的商品
queryset = Goods.objects.all()[:10]
#序列化器
serializer_class = GoodsSerializer
以上两种方法都能获取商品详情的前10条数据,如果当我们需要分页,那么以下的方法就完全能够实现此功能
# 继承ListAPIVIew,只返回前十条数据
class GoodsListAPIView(generics.ListAPIView):
# 得到前10条数据
queryset = Goods.objects.all()
# 序列化器配置
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
# 配置分页制定类
接下就是在setting中配置分页
以后REST_FRAMEWORK的配置都在这里
REST_FRAMEWORK = {
#rest_framework目录下的pagination.py文件PageNumberPagination类
'DEFAULT_PAGINATION_CLASS': "rest_framework.pagination.PageNumberPagination",
#每页显示10条数据
'PAGE_SIZE': 10,
}
通过上述配置,我们看到的django_rest_framework返回的数据就是带有分页的了,每页是10条,分了多页
当然我们还不满足当前的功能,想要动态添加页数,以及动态的每页显示几条数据
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.pagination import PageNumberPagination
from .models import Goods
from .serializer import GoodsSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import mixins
from rest_framework import viewsets
from goods.filters import GoodsFilter
# 配置分页
class GoodsPagination(PageNumberPagination):
#每页多少条数据
page_size = 4
#使用默认字段,每页多少条数据
page_size_query_param = 'size'
#每页最大多少条
max_page_size = 100
page_query_param = "page"
# 页码的定义,默认是page
class GoodsListViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.CreateModelMixin):
# 得到前10条数据
queryset = Goods.objects.all()
# 序列化器配置
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
# 配置分页制定类
filter_backends = (DjangoFilterBackend,SearchFilter,OrderingFilter)
# #配置过滤器
# filter_fields = ('name', 'shop_price')
# #配置过滤器字段
#自定义过滤器
filter_class=GoodsFilter
# 配置搜索 ^表示以什么开头,=表示精准搜索
search_fields = ('name','goods_brief')
#配置排序
ordering_fields = ('name','add_time','shop_price')
#下面是写的过滤的另一种方法
# def get_queryset(self):
# # return Goods.objects.filter(shop_price__gte=100)
# queryset = Goods.objects.all()
# #得到输入的最小价格
# min_price=self.request.query_params.get('min_price',0)
# if min_price:
#
# queryset=queryset.filter(shop_price__gt=int(min_price))
#
# return queryset
上面的我们写的自定义的过滤器是在filiters.py文件中自定义的GoodsFilter一个类,代码如下
from django_filters import rest_framework as filters
from rest_framework import generics
from goods.models import Goods
#商品自定义过滤器
class GoodsFilter(filters.FilterSet):
#最小价格,gte大于或等于
min_price = filters.NumberFilter(name="shop_price", lookup_expr='gte')
# 最大价格
max_price = filters.NumberFilter(name="shop_price", lookup_expr='lte')
name = filters.CharFilter(name='name',lookup_expr='icontains')
#模糊查找名字
class Meta:
model = Goods
fields = ['min_price', 'max_price','name']
接下来我们就是在对应的 urls.py文件中配置对应的路由
from rest_framework.documentation import include_docs_urls
from goods.views import GoodsListViewSet
from rest_framework.routers import DefaultRouter
router=DefaultRouter()
#实例化rest_framework封装好的类
router.register(r'goods',GoodsListViewSet)
#注册路由url是...../goods,的对应的类
urlpatterns = [
"""
url(r'docs/',include_docs_urls(title='硅谷商店')),
#rest_framework API接口数据显示的主页
#reset_framework接口主页,
url(r'^api-auth/',include('rest_framework.urls',namespace='reset_framework')),
url(r'^',include(router.urls))
#过滤参数的url
]
注意我们在使用rest_framework和django自带的过滤器中一定要在setting中的INSTALLED_APPS中注册对应的APP
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig',
'trade.apps.TradeConfig',
'goods.apps.GoodsConfig',
'user_operation.apps.UserOperationConfig',
'DjangoUeditor',
'xadmin',
'crispy_forms',
#以下两个是我们要注册的app
'rest_framework',
'django_filters'
]