【Vue+Django REST framework实战】第4章——商品列表页

网友投稿 530 2022-10-18

【Vue+Django REST framework实战】第4章——商品列表页

【Vue+Django REST framework实战】第4章——商品列表页

django的view实现商品列表页

djangorestframework中文文档:

= [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'docs/', include_docs_urls(title="慕学生鲜")), ]

重写分页组件

from rest_framework.pagination import PageNumberPaginationclass GoodsPagination(PageNumberPagination): page_size = 12 page_size_query_param = 'page_size' page_query_param = "page" max_page_size = 100

商品列表数据接口:

from rest_framework.routers import DefaultRouterrouter = DefaultRouter() #配置goods的urlrouter.register(r'goods', GoodsListViewSet, base_name="goods")

from rest_framework import filtersfrom django_filters.rest_framework import DjangoFilterBackendclass GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ 商品列表页, 分页, 搜索, 过滤, 排序 """ # throttle_classes = (UserRateThrottle, ) queryset = Goods.objects.all() serializer_class = GoodsSerializer pagination_class = GoodsPagination # authentication_classes = (TokenAuthentication, ) filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_class = GoodsFilter search_fields = ('name', 'goods_brief', 'goods_desc') ordering_fields = ('sold_num', 'shop_price') def retrieve(self, request, *args, **kwargs): instance = self.get_object() instance.click_num += 1 instance.save() serializer = self.get_serializer(instance) return Response(serializer.data)

定义商品过滤类

class GoodsFilter(django_filters.rest_framework.FilterSet): """ 商品的过滤类 """ pricemin = django_filters.NumberFilter(name='shop_price', help_text="最低价格",lookup_expr='gte') pricemax = django_filters.NumberFilter(name='shop_price', lookup_expr='lte') top_category = django_filters.NumberFilter(method='top_category_filter') def top_category_filter(self, queryset, name, value): return queryset.filter(Q(category_id=value)|Q(category__parent_category_id=value)|Q(category__parent_category__parent_category_id=value)) class Meta: model = Goods fields = ['pricemin', 'pricemax', 'is_hot', 'is_new']

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:kbframe 一款基于Laravel框架开发的现代化二次开发框架
下一篇:使用Mybatis更新时候只更新变更部分的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~